linux进程的软中断通信
编写一段程序实现进程的软中断通信,要求:
①使用系统调用fork()创建两个子进程,再用系统调用signal()让父进程捕捉键盘上来的中断信号(即按ctrl+c键);当捕捉到中断信号后,父进程用系统调用Kill()向两个子进程发出信号,子进程捕捉到信号后分别输出下列信息后终止:
Child Processll is Killed by Parent!
Child Processl2 is Killed by Parent!
父进程等待两个子进程终止后,输出如下的信息后终止。
Parent Process is Killed!
②在上面的程序中增加语句signal (SIGNAL, SIG-IGN) 和signal (SIGQUIT, SIG-IGN), 观察执行结果,并分析原因。
由于原题中的signal (SIGNAL, SIG-IGN)权限过高,已经被当下的linux的系统所弃用,在此将增加语句signal (SIGNAL, SIG-IGN)更改成增加语句signal(SIGINT,SIG_IGN)。这里,signal(SIGINT,SIG_IGN)和signal(SIGQUIT,SIG_IGN)分别为忽略键信号以及忽略中断信号。
第一步,当收到中断信号或者五秒内没有输入的时候,会出现下面的效果。
这里还是使用gedit编辑器来创建c语言文件,在终端中输入以下命令创建一个c语言文件,可以直接ctrl+c 、ctrl+v复制下面的源代码进process.c。
gedit process.c
源代码如下:
#include<stdio.h>
#include<signal.h>
#include<unistd.h>
void waiting(),stop(),alarming();
int wait_mark;
main()
{
int p1,p2;
if(p1=fork())//创建子进程p1
{
if(p2=fork())//创建子进程p2
{
wait_mark=1;
signal(SIGINT,stop); //接收到^c信号,转stop
signal(SIGALRM,alarming);//接受SIGALRM,转alarming
waiting();
kill(p1,16); //向p1发软中断信号16
kill(p2,17); //向p2发软中断信号17
wait(0);wait(0);//同步,等待前面的所有子进程全部执行完才继续
printf("parent process is killed!\n");
exit(0);
}else{
wait_mark=1;
signal(17,stop);
signal(SIGINT,SIG_IGN);
while (wait_mark!=0);
lockf(1,1,0);
printf("child process2 is killed by parent!\n");
lockf(1,0,0);
exit(0);
}
}else{
wait_mark=1;
signal(16,stop);
signal(SIGINT,SIG_IGN);
while (wait_mark!=0)
lockf(1,1,0);//lockf(fd,1,0)是给fd文件上锁
printf("child process1 is killed by parent!\n");
lockf(1,0,0);//解锁
exit(0);
}
}
void waiting()
{
sleep(5);
if (wait_mark!=0)
kill(getpid(),SIGALRM);
}
void alarming()
{
wait_mark=0;
}
void stop()
{
wait_mark=0;
}
以上的源代码都是用c语言完成,运行环境是ubuntu16.04,编译用gcc。编译方法如下图,给process另起名字为pro,然后输出的时候可以用“./pro”来输出。
gcc process.c -o pro
第二、增加signal(SIGQUIT,SIG_IGN)语句,signal(SIGQUIT,SIG_IGN)是忽略中断信号,在子进程中加入signal (SIGQUIT, SIG-IGN),相应的中断信号就被忽略,只有父进程被中断。运行时,只给出一次中断信号,然后只有父进程被终结。运行结果如下
第二步的源代码如下
#include<stdio.h>
#include<signal.h>
#include<unistd.h>
int pid1,pid2;
int EndFlag=0;
int pf1=0;
int pf2=0;
void IntDelete()
{
kill(pid1,16);
kill(pid2,17);
}
void Int1()
{
printf("child process 1 is killed !by parent\n");
exit(0);
}
void Int2()
{
printf("child process 2 is killed !by parent\n");
exit(0);
}
main()
{
int exitpid;
if(pid1=fork())
{
if(pid2=fork())
{
signal(SIGINT,IntDelete);
waitpid(-1,&exitpid,0);
waitpid(-1,&exitpid,0);
printf("parent process is killed\n");
exit(0);
}
else
{
signal(SIGQUIT, SIG_IGN);//signal(SIGQUIT,SIG_IGN)忽略中断信号
signal(17,Int2);
pause();
}
}
else
{
signal(SIGQUIT, SIG_IGN);//signal(SIGQUIT,SIG_IGN)忽略中断信号
signal(16,Int1);
pause();
}
}