当前位置: 技术问答>linux和unix
Linux信号机制有关问题
来源: 互联网 发布时间:2016-03-12
本文导语: 代码如下: #include #include #include void waiting(),stop(); int wait_mark; main() { int p1,p2,stdout; while((p1=fork())==-1); /*创建子进程p1*/ if (p1>0){ wait_mark=1; signal(SIGINT,stop); /*接...
代码如下:
#include
#include
#include
void waiting(),stop();
int wait_mark;
main()
{
int p1,p2,stdout;
while((p1=fork())==-1); /*创建子进程p1*/
if (p1>0){
wait_mark=1;
signal(SIGINT,stop); /*接收到^c信号,转stop*/
waiting();
kill(p1,16); /*向p1发软中断信号16*/
wait(0); /*同步*/
printf("Parent process is killed!n");
exit(0);
}
else
{
wait_mark=1;
signal(16,stop); /*接收到软中断信号16,转stop*/
waiting();
lockf(stdout,1,0);
printf("Child process 1 is killed by parent!n");
lockf(stdout,0,0);
exit(0);
}
}
void waiting()
{
while(wait_mark!=0);
}
void stop()
{
wait_mark=0;
}
预期结果为:系统调用signal( )让父进程捕捉键盘上来的中断信号(即按^c键);捕捉到中断信号后,父进程用系统调用kill( )向两个子进程发出信号,子进程捕捉到信号后分别输出下列信息后终止:
Child process1 is killed by parent!
父进程等待两个子进程终止后,输出如下的信息后终止:
Parent process is killed!
但执行结果为:按^c键后,只输出了Parent process is killed!而没有子进程那句...请问是为什么呢?
#include
#include
#include
void waiting(),stop();
int wait_mark;
main()
{
int p1,p2,stdout;
while((p1=fork())==-1); /*创建子进程p1*/
if (p1>0){
wait_mark=1;
signal(SIGINT,stop); /*接收到^c信号,转stop*/
waiting();
kill(p1,16); /*向p1发软中断信号16*/
wait(0); /*同步*/
printf("Parent process is killed!n");
exit(0);
}
else
{
wait_mark=1;
signal(16,stop); /*接收到软中断信号16,转stop*/
waiting();
lockf(stdout,1,0);
printf("Child process 1 is killed by parent!n");
lockf(stdout,0,0);
exit(0);
}
}
void waiting()
{
while(wait_mark!=0);
}
void stop()
{
wait_mark=0;
}
预期结果为:系统调用signal( )让父进程捕捉键盘上来的中断信号(即按^c键);捕捉到中断信号后,父进程用系统调用kill( )向两个子进程发出信号,子进程捕捉到信号后分别输出下列信息后终止:
Child process1 is killed by parent!
父进程等待两个子进程终止后,输出如下的信息后终止:
Parent process is killed!
但执行结果为:按^c键后,只输出了Parent process is killed!而没有子进程那句...请问是为什么呢?
|
你在子进程中加上signal(SIGINT, SIG_IGN);就可以了。
当你按Ctrl+C时子进程也收到了^C信号,子进程按照默认处理退出,收不到16信号了。所以也就打印不出来
当你按Ctrl+C时子进程也收到了^C信号,子进程按照默认处理退出,收不到16信号了。所以也就打印不出来
|
顶下1楼的