- 论坛徽章:
- 0
|
我在linux下写的程序,目的是当按下中断键时,父进程给子进程发出信号,子进程打印结束语句,结束运行。然后父进程回到中断点继续运行。但结果为什么和我想的不一样。
另外,如果我不用按中断键的方式触发信号,那么如何保证父进程一定是在子进程已经初始化了sigaction(SIGUSR1, &cact, NULL);后,对子进程进行信号触发。
请各位高手,多多指教!!!小妹在此多些了!!
#include<stdio.h>;
#include<stdlib.h>;
#include<string.h>;
#include<unistd.h>;
#include<signal.h>;
#include<sys/types.h>;
pid_t pid, ppid;
void p_action(int sig)
{
printf("\nparent caught signal" ;
sleep(1);
kill(pid,SIGUSR1);
}
void c_action(int sig)
{
printf("\nchild caught signal" ;
exit();
}
main()
{
void p_action(int), c_action(int);
static struct sigaction pact, cact;
pact.sa_handler=p_action;
sigfillset(&(pact.sa_mask));
sigaction(SIGINT, &pact, NULL);
switch(pid=fork())
{
case -1: {
perror("synchro" ;
exit(1);
}
case 0: {
cact.sa_handler=c_action;
sigaction(SIGUSR1, &cact, NULL);
ppid=getppid();
sleep(5);
printf("\nchild process1" ;
sleep(5);
printf("\nhild process2" ;
sleep(5);
printf("\nchild process3" ;
sleep(5);
printf("\nchild process4" ;
exit(0);
}
default: {
sleep(5);
printf("\nparent process1" ;
sleep(5);
printf("\nparent process2" ;
sleep(5);
printf("\nparent process3" ;
sleep(5);
printf("\nparent process4");
sleep(5);
printf("\nparent process5");
exit(0);
}
}
}
- [/code][code][quote][/quote]
复制代码 |
|