开发者

How can parents waits all child processes finish then exit when it receives SIGINT?

开发者 https://www.devze.com 2023-04-08 01:57 出处:网络
I\'m writing a multi process program in C. I hope parents process can wait all child processes finish then exit when

I'm writing a multi process program in C.

I hope parents process can wait all child processes finish then exit when it receives SIGINT.

I have two questions.

  1. How can parents record each pid of child process it forked. Child process may finis开发者_开发知识库h before recording function run on main process.

  2. If parents has no idea about how many child processes it has. How can he wait all child process finish.

Thanks in advance.


You record the pid of child processes as you fork them (if required). call waitpid in a loop with pid = 0 it will either return a pid of a process that exited or return -1 and if errno = ECHILD you have no slaves left.


Keep calling wait(2) in a loop. Every time wait() returns, you'll get back the PID of the exited child and its status. The status will tell you, whether it exited normally (with an exit code) or due to a signal. Something like this (not tested):

#include <sys/types.h>
#include <sys/wait.h>
...
pid_t    pid;
int      status;
...
while ((pid = wait(&status)) > 0) {
        printf("Child %lu ", (unsigned long)pid);
        if (WIFEXITED(status))
                printf("exited with status %d\n", WEXITSTATUS(status));
        else if (WIFSIGNALED(status))
                printf("killed by signal %d\n", WTERMSIG(status));
        else if (WIFSTOPPED(status))
                printf("stopped by signal %d\n", WSTOPSIG(status));
        else if (WIFCONTINUED(status))
                printf("resumed\n");
        else
                warnx("wait(2) returned for no discernible reason");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消