0

I am trying to send a child's pid to his father using SIGUSR1 and sigqueue. But the signal is never sent, or it appears not to be sent.

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

void handler(int signum, siginfo_t *info, void *extra)
{
    void *ptr_val = info->si_value.sival_ptr;
    int int_val = info->si_value.sival_int;
    printf("Child: Father, I am %d!\n",int_val);
}

int main()
{
    int pid;

    printf("Father: I am %d\n",getpid());

    if ( (pid=fork()) <0 )
    {
        perror("fork");
        exit(EXIT_FAILURE);
    }
    else
        if ( pid==0 )
        {
            printf("Child: I am My father is %d.\n",getppid());
            sigqueue(getppid(),SIGUSR1,(const union sigval) getpid());
        }
        else
        {
            struct sigaction action;
            sigset_t mask;
            sigemptyset(&mask);
            sigaddset(&mask,SIGUSR1);
            action.sa_flags = SA_SIGINFO;
            action.sa_mask =mask;
            action.sa_sigaction = &handler;

            if (sigaction(SIGUSR1,&action,NULL)==-1)
            {
                perror("sigaction");
                exit(EXIT_FAILURE);
            }
            printf("Father: Welcome home, son!\n");
        }

    return 0;
}

Running the code above I get the following output:

Father: I am 18990
Father: Welcome home, son!
Child: My father is 18990.

And that's not all. If I run it again, all my apps close(editor,terminal,etc.) and I need to sign in again. (kind of a switch user operation) What's wrong with the code? Thanks.

4

1 回答 1

2

未捕获信号的原因是父级在子级排队信号之前退出。只需在父级内部添加一个延迟,您就可以看到它捕获了信号。

我在系统上为您的同一程序获得的不同输出进一步加强了这一事实

Father: I am 18990
Father: Welcome home, son!
Child: My father is 1.

孩子将父亲的 pid 记为 1,因为父亲已经离开,孩子成为孤儿并被 init 收养。

一个非常相关的问题

getpid 和 getppid 返回两个不同的值

于 2014-07-19T14:25:53.440 回答