• 进程软中断通信


    描述

    使用系统调用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个值:
    这里写图片描述

  • 相关阅读:
    修改手机端radio 样式
    css ul li 左对齐,换行
    8- 类
    virtualbox虚拟机上网方式
    HTTP请求头详解
    出差总结-2017-11-24
    Some characters cannot be mapped using "GBK" ...
    tortoisesvn与eclipse-svn的删除操作区别
    sql
    setInterval方法, clearInterval
  • 原文地址:https://www.cnblogs.com/EIMadrigal/p/9248196.html
Copyright © 2020-2023  润新知