英文:
How to wait for a set of child processes (and only them) without polling and without eating up the exit code of other people child processes?
问题
如何等待一组子进程(只等待它们),而不进行轮询,也不捕获其他子进程的退出代码?
是否可以为每个子进程的文件描述符 0 创建一个管道,然后使用 select() 函数等待这些文件描述符?
是否需要使用 select() 函数的 exceptfds 参数?
英文:
How to wait for a set of child processes (and only them) without polling and without eating up the exit code of other people child processes?
Is it an idea, to create a pipe for every fd 0 of every child and use select() to wait for these fds?
Would one have to use the exceptfds parameter of select()?
答案1
得分: 3
如果你能将它们都作为同一进程组的一部分,你可以使用waitpid
的否定进程组ID。
例如:
pid_t first = fork();
if (first == 0) {
// ... 线程函数
exit(0);
}
setpgid(first, 0); // 创建一个新的进程组
for (int i = 0; i < 10; i++) {
pid_t pid = fork();
if (pid == 0) {
// ... 线程函数
exit(0);
}
setpgid(pid, first); // 加入进程组
}
int status;
waitpid(-first, &status, WUNTRACED);
这将等待以这种方式创建的进程,但不会等待其他子进程,并且不会消耗其他退出代码。
如果您打算在子进程中调用任何exec()
函数,您应该确保在那之前设置进程组ID。您可以通过在主进程和子进程中都设置它来实现这一点。所以对于第一个,你可以使用:
pid_t first = fork();
if (first == 0) {
setpgid(0, 0);
execv(filename, args);
}
setpgid(first, 0);
对于其他进程,使用setpgid(0, first)
。
你需要包含<unistd.h>
和<sys/wait.h>
。
英文:
If you can make them all part of the same process group, you can use the negated process group id for waitpid
.
For example
pid_t first = fork()
if(first == 0) {
// ... thread function
exit(0);
}
setpgid(first, 0); // creates a new process group
for(int i=0; i<10; i++)
{
pid_t pid = fork();
if(pid == 0)
{
// ... thread function
exit(0);
}
setpgid(pid, first); // joins the process group
}
int status;
waitpid(-first, &status, WUNTRACED);
This will wait for the processes created this way, but not for other child processes, and does not eat up other exit codes.
If you intend on calling any of the exec()
functions in the child process, you should ensure that the process group id is set before that. You can do this by setting it in both the main and child process. So for the first one, you would use
pid_t first = fork()
if(first == 0) {
setpgid(0, 0);
execv(filename, args);
}
setpgid(first, 0);
And setpgid(0, first)
for the others.
You'll need to include <unistd.h>
and <sys/wait.h>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论