-
用系统调用函数fork( )创建两个子进程,再用系统调用函数signal()让父进程捕捉信号SIGINT(用kill命令来触发),当捕捉到中断信号后,父进程用系统调用函数kill()向两个子进程发出信号,子进程捕捉到父进程发来的信号后,分别输出下列信息后终止:
Child process 1 is killed by parent!
Child process 2 is killed by parent!父进程等待两个子进程终止后,输出以下信息后终止:
Parent process exit!
分析过程:
父进程: 创建两个子进程,调用signal函数捕捉SIGINT信号–>func(), 在func函数中,使用kill发送信号SIGHUP 给子进程.然后 wait(NULL)
子进程1: 调用signal函数捕捉SIGHUP信号,执行函数func1,输出一句话,然后结束。
子进程2: 调用signal函数捕捉SIGHUP信号,执行函数 func2,输出一句话,然后结束。
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
pid_t pid=1,pid1=1; //测试pid数值传递
void fatherfun(int arg)
{
//printf("pid1=%d pid2=%d\n",pid,pid1);
kill(pid, SIGHUP);
kill(pid1, SIGHUP);
}
void child1(int arg)
{
printf("child1 process was killed by father process\n");
exit(0);
}
void child2(int arg)
{
printf("child2 process was killed by father process\n");
exit(0);
}
int main()
{
//1,注册捕捉信号SIGINT
signal(SIGINT, fatherfun);
pid = fork();
if(pid < 0){
perror("fork failed\n");
return -1;
}
if(pid > 0){
printf("test father pid=%d\n",getpid());
pid1 = fork();
if(pid1 < 0){
perror("fork failed\n");
return -1;
}
//父进程等待接收捕捉信号
if(pid1 > 0){
wait(NULL);
wait(NULL);
printf("father process exit");
exit(0);
}
//子进程2等待接收父进程发送的信号
if(pid1 == 0){
pid1 = getpid();
signal(SIGHUP, child2);
while(1);
}
}
//子进程1等待接收父进程发送的信号
if(pid == 0){
pid = getpid();
signal(SIGHUP, child1);
while(1);
}
return 0;
}