进程软中断通信

描述

使用系统调用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 
#include 
#include 
#include 
#include 
#include 

int wait_flag = 1;

void stop1();
void stop2();

int main(int argc,char** argv)
{
    pid_t pid1,pid2;

    signal(2,stop1);   //signal 3 is ctrl+\,signal 2 is ctrl+c

    while((pid1 = fork()) == -1);   
    if(pid1 > 0)      //now is in the parent process
    {
        while((pid2 = fork()) == -1);   //creat child process 2
        if(pid2 > 0)
        {
            sleep(5);       //sleep函数被信号中断后,就会导致延时失效,直接跳到sleep的下一行
            kill(pid1,16);  //kill process1,send 16
            wait(0); 
            kill(pid2,17); //kill process2, send 17
            wait(0);
            printf("\nParent process is killed!\n");
            exit(0);
        }
        else
        {
            signal(17,stop2);   //wait for 2 about 17
            while(wait_flag)
                ;

            printf("\nChild process 2 is killed by parent!\n");
            exit(0);
        }
    }
    else
    {
        signal(16,stop2);
        while(wait_flag)
            ;

        printf("\nChild process 1 is killed by parent!\n");
        exit(0);   //execute normally and quit
    }
}

void stop1()
{
    printf("\nParent process catches the interruption signal!\n");
}

void stop2()
{
    wait_flag = 0;
    printf("\nChild process catches the interruption signal!\n");
}

结果

5s内没有按终止键:
进程软中断通信_第2张图片
5s内按下ctrl+c:
进程软中断通信_第3张图片

系统调用signal(sig,function):捕捉中断信号sig后执行function规定的操作。
参数定义:int sigvoid* func()
sig共有19个值:
进程软中断通信_第4张图片

你可能感兴趣的:(操作系统)