编制一段程序,使用系统调用fork()创建两个子进程,再用系统调用signal()让父进程捕捉键盘上来的中断信号(即按Del键),当捕捉到中断信号后,父进程用系统调用kill()向两个子进程发出信号
代码:
#include<stdio.h>
#include<unistd.h>//添加fork()函数头文件
#include<signal.h>//signal头文件
#include<stdlib.h>//exit需头文件
int wait_mark;//等待标志
void waiting(){while(wait_mark!=0);}
void stop(){wait_mark=0;}
int main(){
int p1,p2;
while((p1=fork())==-1);//创建子进程1
if(p1==0){//sub1
printf("p1\n");
wait_mark=1;
//使输入ctrl+c或者delete程序没反应,可按ctrl+/结束程序
signal(SIGINT,SIG_IGN);
signal(16,stop);//将信号16于stop函数关联
waiting();
//锁定屏幕输出,不让其他进程可以输出到屏幕
lockf(1,1,0);
printf("child process 1 is killed\n");
lockf(1,0,0);//解锁,实现进程互斥
exit(0);
}else{
while((p2=fork())==-1);//在父进程中接着创建子进程2
if(p2==0){//sub2
printf("p2\n");
wait_mark=1;
signal(SIGINT,SIG_IGN);
signal(17,stop);
waiting();
lockf(1,1,0);
printf("child process 2 is killed\n");
exit(0);
}else{
printf("parent\n");
wait_mark=1;
signal(SIGINT,stop);
waiting();
kill(p1,16);
kill(p2,17);
wait(0);//在没有唤醒的情况下,该进程处于等待状态
wait(0);
printf("parent process is killed!\n");
exit(0);
}
}
return 0;
}
运行截图: