waitpid - 第一个参数 pid=-1 和 pid=0 之间的区别
waitpid - difference between first parameter pid=-1 and pid=0
我正在阅读 http://www.tutorialspoint.com/unix_system_calls/waitpid.htm 关于 waitpid
函数的内容。它说的是第一个参数 pid,
-1 meaning wait for any child process.
0 meaning wait for any child process whose process group ID is equal to that of the calling process.
请问"any child process"是什么意思,谁的子进程?什么样的情况需要使用-1这个值?
所谓“任何 child 进程”,是指作为调用 waitpid
.
进程的 child 的任何进程
如果您想等待任何 children,您可以使用 -1 的 pid
参数。最常见的用法可能是当你有多个 children 并且你知道至少有一个已经退出,因为你收到了 SIGCHLD
。您想要为每个已退出的 child 调用 waitpid
,但您不确切知道哪些已退出。所以你这样循环:
while (1) {
int status;
pid_t childPid = waitpid(-1, &status, WNOHANG);
if (childPid <= 0) {
break;
}
// Do whatever you want knowing that the child with pid childPid
// exited. Use status to figure out why it exited.
}
忽略进程的 pid 为 1 的情况(在某些进程名称空间中 - 在这种情况下,孤立进程将被重新定义),0
和 -1
之间只有一个区别。
使用 -1
,将等待任何 child。使用0
,调用setpgid
的children将不会被等待。
"child" 被定义为由 fork
从您的进程创建的进程(但不是来自任何 child - 您不能等待 grandchildren,尽管Linux 我 认为 你可以通过轮询 /proc/<pid>
来做类似的事情。请注意 execve
不会 影响任何事情。
我正在阅读 http://www.tutorialspoint.com/unix_system_calls/waitpid.htm 关于 waitpid
函数的内容。它说的是第一个参数 pid,
-1 meaning wait for any child process.
0 meaning wait for any child process whose process group ID is equal to that of the calling process.
请问"any child process"是什么意思,谁的子进程?什么样的情况需要使用-1这个值?
所谓“任何 child 进程”,是指作为调用 waitpid
.
如果您想等待任何 children,您可以使用 -1 的 pid
参数。最常见的用法可能是当你有多个 children 并且你知道至少有一个已经退出,因为你收到了 SIGCHLD
。您想要为每个已退出的 child 调用 waitpid
,但您不确切知道哪些已退出。所以你这样循环:
while (1) {
int status;
pid_t childPid = waitpid(-1, &status, WNOHANG);
if (childPid <= 0) {
break;
}
// Do whatever you want knowing that the child with pid childPid
// exited. Use status to figure out why it exited.
}
忽略进程的 pid 为 1 的情况(在某些进程名称空间中 - 在这种情况下,孤立进程将被重新定义),0
和 -1
之间只有一个区别。
使用 -1
,将等待任何 child。使用0
,调用setpgid
的children将不会被等待。
"child" 被定义为由 fork
从您的进程创建的进程(但不是来自任何 child - 您不能等待 grandchildren,尽管Linux 我 认为 你可以通过轮询 /proc/<pid>
来做类似的事情。请注意 execve
不会 影响任何事情。