如何在此处使用 waitpid() 命令来等待其子级的终止,然后显示 PID。
for(int i=0; i < 5 ;i++)
{
if(pid > 0)
{
pid = fork();
c++;
if(pid==0)
{
printf("child: %d \n",c);
printf("child process with pid self %d \n", getpid());
}
}
}
最佳答案
你应该像这样重构你的循环:
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
...
pid_t pid;
for (int i = 0; i < 5; i++) {
pid = fork();
if (pid == 0) {
printf("child process with pid %d\n", getpid());
...
exit(0);
} else if (pid > 0) {
/* the child has been forked and we are in the parent */
} else {
/* could not fork child */
}
}
int status;
while ((pid = waitpid(-1, &status, 0))) {
if (pid == -1 && errno == ECHILD) {
break;
} else if (pid == -1) {
perror("waitpid");
} else if (WIFEXITED(status)) {
printf("%d exited, status=%d\n", pid, WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("%d killed by signal %d\n", pid, WTERMSIG(status));
} else if (WIFSTOPPED(status)) {
printf("%d stopped by signal %d\n", pid, WSTOPSIG(status));
} else if (WIFCONTINUED(status)) {
printf("%d continued\n", pid);
}
}
请注意在子 block 末尾包含对 exit
的调用。这是为了防止子进程继续执行循环所必需的。
第二个循环应该运行,直到所有子循环都终止。
关于c - 单父进程的多个子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42178248/