调用fork()创建两个子进程,父进程接受SIGINT信号中断,之后发送16和17中断子进程。
1 #include <sys/wait.h> 2 #include <sys/types.h> 3 #include <unistd.h> 4 #include <signal.h> 5 #include <iostream> 6 #include <cstdlib> 7 using namespace std; 8 int flag; 9 void stop(int signo) { 10 flag = 0; 11 if (signo == SIGINT){ 12 cout << "recv SIGINT" << endl; 13 } 14 else if (signo == 16) { 15 cout << "recv 16" << endl; 16 } 17 else if (signo == 17) { 18 cout << "recv 17" << endl; 19 } 20 } 21 22 int main() 23 { 24 int pid1; 25 int pid2; 26 if ((pid1 = fork()) < 0) { 27 cerr << "fork1 error" << endl; 28 exit(0); 29 } 30 if (pid1 > 0) { 31 if ((pid2 = fork()) < 0) { 32 cerr << "fork2 error" << endl; 33 exit(0); 34 } 35 if (pid2 > 0) { 36 flag = 1; 37 signal(SIGINT, stop); 38 while (flag); 39 kill(pid1, 16); 40 kill(pid2, 17); 41 wait(NULL); 42 wait(NULL); 43 cout << "Parent process is killed !!" << endl; 44 exit(0); 45 } 46 else { 47 flag = 1; 48 signal(17, stop); 49 while (flag); 50 cout << "c2" << endl; 51 exit(0); 52 } 53 } 54 else { 55 flag = 1; 56 signal(16, stop); 57 while (flag); 58 cout << "c1" << endl; 59 exit(0); 60 } 61 62 return 0; 63 }
运行后打开另一个终端,用ps aux获取进程pid号
kill -s SIGINT (pid)
向父进程发送SIGINT中断信号。
结果: