c - 使用 sigqueue 和 SIGUSR1 将子 pid 发送给父亲

标签 c signals ipc pid sigqueue

我正在尝试使用 SIGUSR1 和 sigqueue 将 child 的 pid 发送给他的父亲。但是信号从未发送过,或者看起来没有发送过。

#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;
}

运行上面的代码我得到以下输出:

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

这还不是全部。如果我再次运行它,我所有的应用程序都会关闭(编辑器、终端等),我需要重新登录。 (一种切换用户操作)代码有什么问题?谢谢。

最佳答案

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

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

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

child 注意到父亲的 pid 为 1,因为父亲已经退出,留下 child 作为孤儿并被 init 收养。

一个非常相关的问题

getpid and getppid returns two different values

关于c - 使用 sigqueue 和 SIGUSR1 将子 pid 发送给父亲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24841023/

相关文章:

c++ - 有没有比fseek和fwrite更快的写入方法?

c - 迭代字符数组,同时跳过空格

在发送 spider_closed 信号之前调用 Python Scrapy 函数?

linux - lldbinit 中的进程句柄

python - 如何使用 Ctrl-C 优雅地终止 asyncio 脚本?

c - 求函数时间复杂度的准确方法

c - C 结构体中的指针地址

德尔福2009 : How to communicate between Windows service & desktop application under Vista?

sockets - Linux : Unix domain datagram sockets don't follow specification of connect/recv,吗?

Delphi firemonkey进程间通信有可能吗?