【问题标题】:Send child pid using sigqueue and SIGUSR1 to father使用 sigqueue 和 SIGUSR1 将子 pid 发送给父亲
【发布时间】:2014-07-19 13:38:26
【问题描述】:

我正在尝试使用 SIGUSR1 和 sigqueue 将孩子的 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.

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

【问题讨论】:

    标签: c signals ipc pid sigqueue


    【解决方案1】:

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

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

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

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

    一个非常相关的问题

    getpid and getppid returns two different values

    【讨论】:

    • 确实,父母先于孩子退出。我用waitpid来解决它。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-05-27
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 2016-05-25
    • 2018-02-26
    相关资源
    最近更新 更多