【发布时间】:2023-09-03 02:26:01
【问题描述】:
我可以通过父进程杀死一个子进程。但是如果父进程有多个子进程会怎样呢?
例如在下面的代码中,有 1 个父进程和 6 个子进程。父进程终止后如何立即杀死其他六个子进程?
如果您运行此代码,父进程将在 5 秒后终止。在该子进程再过 5 秒(总共 10 秒)后终止。
但是我想在父进程终止后立即杀死6个子进程。所以父进程和6个子进程应该在5秒后终止。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
for(int i=0;i<6;i++) // loop will run 6 times(there are 6 child processes.)
{
if(fork() == 0)
{
printf("Started [son] pid %d from [parent] pid %d\n",getpid(),getppid());
sleep(10); //child waits 10 seconds,then it exitted.
printf("Exitted [son] pid %d from [parent] pid %d\n",getpid(),getppid());
exit(0);
}
}
//parent
sleep(5); //parent will wait 5 seconds than it will exit
printf("Parent terminated\n");
exit(0); //parent terminated.(how can I exit the the other 6 child processes too?)
}
【问题讨论】:
-
阅读手册等待2。
-
@purec 我已经读过,我不希望父母等待孩子。
-
好的...但是当父母等待孩子终止时这是一种常见的做法。
标签: c linux process posix kill-process