0%

进程软中断通信

描述

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

流程图:
image

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

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内没有按终止键:
image

5s内按下ctrl+c:
image

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