在终端中按下ctrl+C,会向当前前台进程以及其子进程发送一个SIGINT信号。实验代码如下:
父进程
#include<signal.h> //for signal
#include<unistd.h> //for fork execlp
#include<iostream>
using namespace std;
void h(int sig)
{
cout<<"father sig:"<<sig<<endl;
exit(0);
}
int main()
{
signal(SIGINT,h);
auto pid = fork();
if(pid>0)
{
cout<<"father"<<endl;
while(1)
{
sleep(0);
}
}
else
{
execlp("./child","child",NULL);
}
}
子进程
#include<iostream>
#include<signal.h>
#include<unistd.h>
using namespace std;
void h(int sig)
{
cout<<"sig:"<<sig<<endl;
exit(0);
}
int main()
{
signal(SIGINT,h);
while(1)
{
sleep(0);
}
}
实验现象
liudelong@liudelong-virtual-machine:~/桌面/test$ ./signal
father
^Cfather sig:2
sig:2