• 进程软中断通信


    描述

    使用系统调用fork()创建两个子进程,再用系统调用signal()让父进程捕捉键盘上发出的中断信号(即按ctrl+c键),当父进程接收到这两个软中断的某一个后,父进程用系统调用kill()向两个子进程分别发出整数值为16和17软中断信号,子进程获得对应软中断信号,然后分别输出下列信息后终止:
    Child process 1 is killed by parent !!
    Child process 2 is killed by parent !!
    父进程调用wait()函数等待两个子进程终止后,输入以下信息,结束进程执行:
    Parent process is killed!!

    流程图

    这里写图片描述

    实现

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <signal.h>
     4 #include <unistd.h>
     5 #include <sys/types.h>
     6 #include <sys/wait.h>
     7 
     8 int wait_flag = 1;
     9 
    10 void stop1();
    11 void stop2();
    12 
    13 int main(int argc,char** argv)
    14 {
    15     pid_t pid1,pid2;
    16 
    17     signal(2,stop1);   //signal 3 is ctrl+\,signal 2 is ctrl+c
    18 
    19     while((pid1 = fork()) == -1);   
    20     if(pid1 > 0)      //now is in the parent process
    21     {
    22         while((pid2 = fork()) == -1);   //creat child process 2
    23         if(pid2 > 0)
    24         {
    25             sleep(5);       //sleep函数被信号中断后,就会导致延时失效,直接跳到sleep的下一行
    26             kill(pid1,16);  //kill process1,send 16
    27             wait(0); 
    28             kill(pid2,17); //kill process2, send 17
    29             wait(0);
    30             printf("
    Parent process is killed!
    ");
    31             exit(0);
    32         }
    33         else
    34         {
    35             signal(17,stop2);   //wait for 2 about 17
    36             while(wait_flag)
    37                 ;
    38 
    39             printf("
    Child process 2 is killed by parent!
    ");
    40             exit(0);
    41         }
    42     }
    43     else
    44     {
    45         signal(16,stop2);
    46         while(wait_flag)
    47             ;
    48 
    49         printf("
    Child process 1 is killed by parent!
    ");
    50         exit(0);   //execute normally and quit
    51     }
    52 }
    53 
    54 void stop1()
    55 {
    56     printf("
    Parent process catches the interruption signal!
    ");
    57 }
    58 
    59 void stop2()
    60 {
    61     wait_flag = 0;
    62     printf("
    Child process catches the interruption signal!
    ");
    63 }
    View Code

    结果

    5s内没有按终止键:
    这里写图片描述
    5s内按下ctrl+c:
    这里写图片描述

    系统调用signal(sig,function):捕捉中断信号sig后执行function规定的操作。
    参数定义:int sigvoid* func()
    sig共有19个值:
    这里写图片描述

  • 相关阅读:
    第六章 虹销雨霁(中)
    第四章 曙光初现(下)
    第三章 曙光初现(上)
    第二章 福祸相伴(下)
    第二章 福祸相伴(上)
    小云(云层-陈霁)的发展史
    小白成长建议(9)-苞丁解牛
    NYoj 116士兵杀敌(二)区间求和,单点更新
    HDU 1754 区间查询,单点更新
    《灯亮or灯灭》 --有个有趣的数论问题
  • 原文地址:https://www.cnblogs.com/EIMadrigal/p/9248196.html
Copyright © 2020-2023  润新知