笔试题,进程与信号

题一:父进程每隔5秒向子进程发送消息,令其打印一句话

 

      1 #include <stdio.h>

      2 #include <unistd.h>

      3 #include <signal.h>

      4 #include <sys/types.h>

      5 

      6 void printMsg(int signo)

      7 {

      8     printf("father send msg to child/n");

      9 };

     10 

     11 main()

     12 {

     13     pid_t pid = fork();

     14     if(pid <0)

     15         exit(0);

     16     if(pid>0)

     17     {

     18         while(1)

     19         {

     20             sleep(5);

     21             kill(pid,SIGUSR1);

     22         }

     23     }

     24     else if(pid == 0)

     25     {

     26         if(signal(SIGUSR1,printMsg)== SIG_ERR)

     27         {

     28             perror("signal");

     29             exit(0);

     30         }

     31         while(1);

     32     }

     33 }

 

题二,按ctrl+c  先父进程打印一句话,后子进程打印一句话

      1 #include <stdio.h>

      2 #include <unistd.h>

      3 #include <signal.h>

      4 #include <sys/types.h>

      5 

      6 void printMsgByFather(int signo)

      7 {

      8     printf("father is over/n");

      9     wait();

     10     exit(0);

     11 };

     12 void printMsgBySon(int signo)

     13 {

     14     sleep(1);

     15     printf("son is over/n");

     16     exit(0);

     17 }

     18 

     19 main()

     20 {   

     21     pid_t pid = fork();

     22     if(pid <0)

     23         exit(0);

     24     if(pid>0)

     25     {   

     26         if(signal(SIGINT,printMsgByFather)== SIG_ERR)

     27         {   

     28             perror("signal");

     29             exit(0);

     30         }

     31         while(1);

     32     }

     33     else if(pid == 0)

     34     {   

     35         if(signal(SIGINT,printMsgBySon)== SIG_ERR)

     36         {   

     37             perror("signal");

     38             exit(0);

     39         }

     40         while(1);

     41     }

     42 }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值