当前位置: 技术问答>linux和unix
请教一个有关信号的问题
来源: 互联网 发布时间:2016-07-07
本文导语: 我刚开始看linux信号,有一道例题是这样的: #include #include #include #include int wait_mark = 1; void waiting(), stop(); int main() { pid_t p1, p2; signal(SIGINT, stop); while((p1=fork()) == -1); if(p1 > 0) ...
我刚开始看linux信号,有一道例题是这样的:
#include
#include
#include
#include
int wait_mark = 1;
void waiting(), stop();
int main()
{
pid_t p1, p2;
signal(SIGINT, stop);
while((p1=fork()) == -1);
if(p1 > 0)
{ ①
while((p2=fork()) == -1);
if(p2 > 0)
{ ②
wait_mark = 1;
waiting();
kill(p1, 10);
kill(p2, 12);
wait();
wait();
printf("Parent process is killed!n");
exit(0);
}
else
{
wait_mark = 1;
signal(12, stop);
waiting();
lockf(1,1,0);
printf("Child process 2 is killed by parent!n");
lockf(1,0,0);
exit(0);
}
}
else
{
wait_mark = 1;
signal(10, stop);
signal(10, stop);
waiting();
lockf(1,1,0);
printf("Child process 1 is killed by parent!n");
lockf(1,0,0);
exit(0);
}
}
void waiting()
{
while(wait_mark != 0);
}
void stop()
{
wait_mark = 0;
}
编译运行后按CTRL-C得到了:
Child process 2 is killed by parent!
Child process 1 is killed by parent!
Parent process is killed!
这个结果应该是没有问题的,
但如果我把signal(SIGINT, stop);这条语句放到①或者②位置时,得到的是:
Child process 2 is killed by parent!
Parent process is killed!
为什么会少一条输出啊?
#include
#include
#include
#include
int wait_mark = 1;
void waiting(), stop();
int main()
{
pid_t p1, p2;
signal(SIGINT, stop);
while((p1=fork()) == -1);
if(p1 > 0)
{ ①
while((p2=fork()) == -1);
if(p2 > 0)
{ ②
wait_mark = 1;
waiting();
kill(p1, 10);
kill(p2, 12);
wait();
wait();
printf("Parent process is killed!n");
exit(0);
}
else
{
wait_mark = 1;
signal(12, stop);
waiting();
lockf(1,1,0);
printf("Child process 2 is killed by parent!n");
lockf(1,0,0);
exit(0);
}
}
else
{
wait_mark = 1;
signal(10, stop);
signal(10, stop);
waiting();
lockf(1,1,0);
printf("Child process 1 is killed by parent!n");
lockf(1,0,0);
exit(0);
}
}
void waiting()
{
while(wait_mark != 0);
}
void stop()
{
wait_mark = 0;
}
编译运行后按CTRL-C得到了:
Child process 2 is killed by parent!
Child process 1 is killed by parent!
Parent process is killed!
这个结果应该是没有问题的,
但如果我把signal(SIGINT, stop);这条语句放到①或者②位置时,得到的是:
Child process 2 is killed by parent!
Parent process is killed!
为什么会少一条输出啊?
|
signal(SIGINT, stop)放在1处,应该是
Child process 2 is killed by parent!
Parent process is killed!
signal(SIGINT, stop)放在2处,应该是只有
Parent process is killed!
这是因为ctrl+c发送的INT信号是给整个前台进程组的,所以其实程序里所有的进程(父进程,p1子进程和p2子进程)都看到了这个信号。
如果你signal(SIGINT, stop)放在1处,那么只有父进程与p2子进程看得到stop这个猜获函数,p1子进程是执行INT信号的默认操作终止进程。
如果你signal(SIGINT, stop)放在2处,那么只有父进程看到stop这个猜获函数,p1子进程和p2子进程会执行INT信号默认操作终止。
Child process 2 is killed by parent!
Parent process is killed!
signal(SIGINT, stop)放在2处,应该是只有
Parent process is killed!
这是因为ctrl+c发送的INT信号是给整个前台进程组的,所以其实程序里所有的进程(父进程,p1子进程和p2子进程)都看到了这个信号。
如果你signal(SIGINT, stop)放在1处,那么只有父进程与p2子进程看得到stop这个猜获函数,p1子进程是执行INT信号的默认操作终止进程。
如果你signal(SIGINT, stop)放在2处,那么只有父进程看到stop这个猜获函数,p1子进程和p2子进程会执行INT信号默认操作终止。