Linux进程间信号通信

1、 完成一个简单的例子:

进程间的信号通信:

源文件:sigtest.c

#include<sys/file.h>
#include<stdio.h>
#include<signal.h>
#include<unistd.h>
#include<stdlib.h>
voidwaiting();
voidstop();
intwait_mark;
char *pname;
 
main()
{
     intp1,p2,stdout;
 
     while((p1=fork())==-1);
     if(p1>0)//父进程
    {
        while((p2=fork())==-1);
         if(p2>0)//父进程
         {
         Pname=“paraent process“;
signal(SIGINT,stop);
        
            wait_mark=1;
            waiting();
             printf(“I’m %s,get singal!\n”,pname);
             sleep(2);
printf(“I’m  %s,I’m sending singal 10 to p1\n”,pname);
            kill(p1,10);//向P1发送信号10
             kill(p2,12);//向P2发送信号12
            wait(0);//等待子进程退出
sleep(2);
printf(“I’m  %s,I’m sending singal 12 to p1\n”,pname);
 
             wait(0);//等待子进程退出
sleep(2);
             //printf(" parent process  is killed !\n" );
printf(“I’m  %s,I’m quiting\n”,pname);
 
             exit(0);
         }
         else //2号子进程
         {
signal(SIGINT,SIG_IGN);
 
pname=”childprocess 2”;
             wait_mark=1;
            signal(12,stop);
            waiting();
             printf("chlidprocess 2 is killed by parent!\n" );
             exit(0);
         }
}
else//1号子进程
{  
signal(SIGINT,SIG_IGN);
 
pname=”childprocess 1”;
 
         wait_mark=1;
         signal(10,stop);
         waiting();
         printf("chlidprocess 1 is killed by parrent!\n" );
         exit(0);
   }
}
 
voidwaiting()
{
    while(wait_mark == 1)//更改全局变量wait_mark,退出等待循环
     {sleep(2);
     Printf(“I’m %s,wainting singal!\n”,pname);
}
}
 
voidstop()
{
    wait_mark=0;//更改全局变量wait_mark,使waiting函数退出
}

观察并解释上述程序的运行结果。


修改后的:


创建两个子进程,父进程捕捉键盘上来的中断信号(即按^c键);捕捉到中断信号后,父进程向两个子进程发出信号,子进程捕捉到信号后分别输出下列信息后终止:Child process1 is killed by parent! Child process2 is killed byparent!父进程等待两个子进程终止后,输出如下的信息后终止:Parent process iskilled!

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值