system()后获取子进程PID
据我了解, system()
调用在内部使用 fork()
和 exec()
但封装了它们以便于处理。
是否可以从使用 system()
调用创建的子进程中获取 PID?
目标:我希望能够在一定的超时后 SIGINT 任何子进程。我可以使用 fork()
和 exec()
重建 system()
函数。但我所需要的只是孩子的PID,也许使用system()
有捷径?
As far as I understand, the system()
call uses internally fork()
and exec()
but encapsulates them for a easier handling.
Is it possible to get the PID from the child process created with the system()
call?
Aim: I want to be able to SIGINT any child process after a certain timeout. I could rebuild the system()
function by using fork()
and exec()
. But all I need is the child's PID and perhaps there is shortcut by using system()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通常,
system()
是同步操作。这意味着在子进程退出之前它不会返回,即当system()
返回时,子进程没有有效的 PID,因为子进程不再存在。Typically,
system()
is a synchronous operation. This means it won't return until the child has exited, i.e. there is no valid PID for the child process whensystem()
returns, since the child process no longer exists.使用
system()
时没有办法(据我所知)。此外,使用system()
还需要启动一个 shell 来执行您的命令,这使得这有点困难。您最好将其替换为fork()
和exec()
。There's no way (that I know of) when using
system()
. Besides, withsystem()
there's the additional step of launching a shell which will execute your command, making this a tad more difficult. You're probably better off replacing it withfork()
andexec()
.我遇到了这个问题。解决方法:
这可能并不总是有效,但大多数时候 system() 的 PID 是父进程的 pid +1(除非你有多个 fork)。
I had this problem. Solved it by:
This might not always work, but most of the time the system()'s PID is the parent's pid +1 (unless you have multiple forks).
但是,有一种方法可以通过 /proc 文件系统执行您想要的操作。您可以浏览进程目录(目录名称是 PID)并检查“状态”文件。其中每个都有一个 PPid 条目指定父 pid。
这样,如果您获得一个将进程的 PID 指定为 PPID 的“状态”文件,那么 /proc 文件系统中的文件夹名称就是您要查找的值。
However, there is a way of doing what you want via the /proc file system. You can go through process directories (directory names are PIDs) and check the "status" files. There's a PPid entry in each of them specifying the parent pid.
This way, if you get a "status" file which specifies the PID of your process as PPID, then its folder name in /proc file system is the value you are looking for.