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()?
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>