日期:2014-05-16  浏览次数:20638 次

关于在父子进程中使用signal函数的问题
各位大侠,我在gcc中,编辑一个程序,源代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>

void handler(int signo)
{
switch(signo)
{
case SIGUSR1:
printf("parent: catch SIGUSR1\n");
break;
case SIGUSR2:
printf("child: catch SIGUSR2\n");
break;
default:
printf("should not be here\n");
break;
}
return;
}

int main(void)
{
pid_t ppid, cpid;

if(signal(SIGUSR1, handler) == SIG_ERR)
{
perror("can't set handler for SIGUSR1");
exit(1);
}

if(signal(SIGUSR2, handler) == SIG_ERR)
{
perror("can't set handler for SIGUSR2");
exit(1);
}

ppid = getpid();

if((cpid = fork()) < 0)
{
perror("fail to fork");
exit(1);
}
else if(cpid == 0)
{
if(kill(ppid, SIGUSR1) == -1)
{
perror("fail to send signal");
exit(1);
}

while(1);
}
else
{
sleep(1);

if(kill(cpid, SIGUSR2) == -1)
{
perror("fail to send signal");
exit(1);
}

printf("kill child\n");

if(kill(cpid, SIGKILL) == -1)
{
perror("fail to send signal");
exit(1);
}

if(wait(NULL) == -1)
{
perror("fail to wait");
exit(1);
}
}

return 0;
}

编译通过,但是,运行结果为:
parent : catch SIGUSR1
kill child 

预期结果应是:
parent:catch SIGUSR1
child:catch SIGUSR2
kill child

请问究竟是哪里出了问题?谢谢赐教!

------解决方案--------------------
楼主是在送分吗
之前发过一个完全一样的帖子了

ppid = getpid();
把这句话放在fork()之后的子进程中执行。。
------解决方案--------------------
父进程发送的信号太快了
先发送了一个SIGUSR2 信号,立马又发送了一个SIGKILL 信号
子进程来不及处理SIGUSR2 信号,就被SIGKILL 信号终止了
在两次发送信号之间添加一个sleep(1)就行了

子进程逻辑
    else if (cpid == 0)
    {
        ppid = getpid();
        if (kill(ppid, SIGUSR1) == -1)
        {
            perror("fail to send signal");
            exit(1);
        }

        while (1);
    }


父进程逻辑,注意第二个sleep(1)
  &nb