发出 "SIGUSR1" 信号时发送退出代码

sending exit code when raise the "SIGUSR1" signal

我正在尝试在引发“SIGUSR1”时发送子进程的退出代码 我写了一个等待进程的处理程序,但它没有正确接收退出代码 相反,它收到 -1

这是我在 main 的代码

void main()
{
    signal(SIGUSR1, handler);
    int pid = fork();
    if (pid == -1)
        perror("error in forking");
    else if (pid == 0)
    {
        printf("\ni am child and my pid %d\n", getpid());
        raise(SIGUSR1);
        exit(100);
    }
    sleep(5);
    printf("\nnow i am the parent and my  = %d\n ", getpid());
}

这是处理程序代码

void handler(int signunm)
{

    int pid, stat_loc;

    pid = wait(&stat_loc);
    if (!(stat_loc & 0x00FF))
        printf("\nI am called with the process %d with value %d\n", pid, stat_loc >> 8);
}

输出类似于

i am child and my pid 45892

I am called with the process -1 with value 4

now i am the parent and my  = 45891

应该是100而不是-1

你应该使用 kill(PPID, SIGUSR1) 函数而不是 raise(SIGUSR1) 函数,这样你就可以向父级发送一个信号来处理它而不是子级本身。您可以通过调用 getppid()

获得 PPID