杀死进程的子进程利用kill(ChildPid, SIGTERM)就可以做到,但是如何杀死子进程的儿子喃,这里要用到一个进程组的概念,kill函数可以利用传递负pid的方法将SIGTERM信号传送给具有相同进程组号的所有进程。
如下是man对kill函数的一个的一个描述
#include
#include
/*
pid>0:signal sig is sent to pid
pid==0:sig is sent to every process in the process group of the current process
pid==-1: sig is sent to every process for which the calling process has permission to send signals, except for process 1 (init)
pid
*/
int kill(pid_t pid, int sig);
测试程序:在Redhat下运行,通过ps的方式来观察子孙进程的创建和销毁
#include
#include
#include
#include
#include
#include
#include
int main(void)
{
pid_t pid;
int stat;
for (;;)
{
pid = fork();
if (pid == 0)
{
/* 将子进程的进程组ID设置为子进程的PID */
setpgrp();
printf("Child process running:pid=%d,pgid=%d\n", getpid(),getpgrp());
printf("Creat grandchild process sleep 20 seconds\n");
/* 子进程创建一个孙子进程 */
system("sleep 20");
exit(0);
}
else if (pid > 0)
{
printf("Parent process pid=%d, pgid=%d\n", getpid(),getpgrp());
printf("Parent process sleep 10 seconds\n");
sleep(10);
/* 利用传递负子进程PID将SIGTERM信号传送给子进程和孙子进程 */
kill(-pid, SIGTERM);
wait(&stat);
printf("All child and grandchild processes with pgid=%d were killed\n", pid);
}
else
printf("Fork fail : %s\n", strerror(errno));
}
return 0;
}