如何在 C++ 中查询子进程
我的 C++ 程序将使用 fork() 和 execv() 生成多个子进程。如何查询这些进程?如果我想关闭一个,我该怎么做?
My c++ program will spawn several child processes using fork() and execv(). How can I query those processes? If I wanted to shut one down, how would I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您
fork
时,子进程中的返回值为0,父进程中的返回值为子进程ID (pid)。然后,您可以使用该 pid 调用
kill
以查看它是否仍在运行,或请求关闭。要检查进程是否正在运行,请使用 0 作为信号,然后检查返回值(0 == 正在运行;-1 == 未运行)。要请求关闭,请使用SIGTERM
作为信号。When you
fork
, the return value is 0 in the child process, and the child's process ID (pid) in the parent process.You can then call
kill
with that pid to see if it's still running, or request a shutdown. To check if the process is running, use 0 as the signal, then check the return value (0 == running; -1 == not running). To request a shutdown, useSIGTERM
as the signal.据我所知,在 fork() 后进程之间进行通信的最佳方式可能是通过套接字(请参阅 socketpair())。
从那里开始,您只需定义通信协议(包括终止请求)就可以使任何事情发挥作用。
Probably the best way that I know of to communicate between processes after a
fork()
is through sockets (see socketpair()).From there, you can probably make anything work by just defining a protocol for communication (including the request to terminate).
调用
fork()
后,您可以使用wait(&status_int)
或waitpid(child_pid, &status_int, WNOHANG)
检测子项的返回状态,如果您不想阻塞等待子项,请使用后者。传递的参数&status_int
将是一个指向int
的指针,它将保存子进程退出后的返回状态。如果您想等待任何分叉进程完成,并且不关心返回值,您可以简单地调用wait(NULL)
,或者对于非阻塞版本,<代码>waitpid(-1,NULL,WNOHANG)。After a call to
fork()
, you can use eitherwait(&status_int)
orwaitpid(child_pid, &status_int, WNOHANG)
to detect the return status of children, using the latter if you don't want to block waiting for a child. The passed argument&status_int
would be a pointer to anint
that will hold the return status of the child process after it has exited. If you want to wait for any forked process to complete, and don't care about the return value, you can simply make a call towait(NULL)
, or for a non-blocking version,waitpid(-1, NULL, WNOHANG)
.