新手求助:一个小程序
我是个新手,提这么简单的问题请大家不要见笑。有这样一个简单的程序,是有关linux信号控制的:
#include<stdio.h>
#include<signal.h>
void waiting(),stop();
int wait_mark;
main()
{
int p1,p2;
while((p1=fork())==-1);
if(p1>0)
{
while((p2=fork())==-1);
if(p2>0)
{
wait_mark=1;
signal(SIGINT,stop);
waiting();
kill(p1,16);
kill(p2,17);
wait(0);
wait(0);
printf("parent process is killed!\n");
exit(0);
}
else
{
wait_mark=1;
signal(17,stop);
waiting();
lockf(stdout,1,0);
printf("process two is killed by parent!\n");
lockf(stdout,0,0);
exit(0);
}
}
else
{
wait_mark=1;
signal(16,stop);
waiting();
lockf(stdout,1,0);
printf("process two is killed by parent!\n");
lockf(stdout,0,0);
exit(0);
}
}
void waiting()
{
while(wait_mark!=0);
}
void stop()
{
wait_mark=0;
}
这个程序在运行时,当按下中断信号CTRL+C(对应SIGINT)时,屏幕只输出父进程信息:parent process is killed!,两个子进程直接被杀死而没有任何输出。但理论上按下CTRL+C时,屏幕应输出:
process one is killed by parent!
process two is killed by parent!
parent process is killed!
多次修改仍不行,终端只有父进程的退出信号。真是头大,束手无策。
望哪位高手能指点一下,在下感激不尽。 nothing related with kernel. 在子进程中屏蔽掉SIGINT,否则子进程收到SIGINT后会退出
like this:
#include<stdio.h>
#include<signal.h>
#include<unistd.h>
#include<sys/types.h>
void waiting(void);
void stop(int);
int wait_mark;
main()
{
pid_t p1,p2;
sigset_t nset,oset;
sigemptyset(&nset);
sigemptyset(&oset);
while((p1=fork())==-1);
if(p1>0)
{
while((p2=fork())==-1);
if(p2>0)
{
wait_mark=1;
signal(SIGINT,stop);
waiting();
kill(p1,SIGSTKFLT);
kill(p2,SIGCHLD);
wait(NULL);
wait(NULL);
fprintf(stderr,"parent process is killed!\n");
exit(0);
}
else
{
sigaddset(&nset,SIGINT);
sigprocmask(SIG_BLOCK,&nset,&oset);
wait_mark=1;
signal(17,stop);
waiting();
lockf(STDOUT_FILENO,1,0);
fprintf(stderr,"process two is killed by parent!\n");
lockf(STDOUT_FILENO,0,0);
sigprocmask(SIG_SETMASK,&oset,NULL);
exit(0);
}
}
else
{
sigaddset(&nset,SIGINT);
sigprocmask(SIG_BLOCK,&nset,&oset);
wait_mark=1;
signal(16,stop);
waiting();
lockf(STDOUT_FILENO,1,0);
fprintf(stderr,"process one is killed by parent!\n");
lockf(STDOUT_FILENO,0,0);
sigprocmask(SIG_SETMASK,&oset,NULL);
exit(0);
}
}
void waiting(void)
{
while(wait_mark!=0);
}
void stop(int sig)
{
printf("pid : %d got signal \" %d \" from parent : %d\n",getpid(),sig,getppid());
wait_mark=0;
} 多谢z兄,回去再去试几次
斑竹见谅,小弟不是有意的 :cry: sure.:-D
页:
[1]