C语言 如何通过 kill 命令将信号从子进程发送到父进程



我正在尝试通过系统调用创建一个子进程fork()然后尝试向父进程发送信号并在屏幕上打印出一些内容。

这是我的代码:-

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
void func1(int signum) {
    if(signum == SIGUSR2) {
        printf("Received sig from childn");
    }
}
int main() {
    signal(SIGUSR2, func1);
    int c = fork();
    if(c > 0) {
        printf("parentn");
    }
    else if(c == -1) {
        printf("No child");
    }
    else {
        kill(getppid(), SIGUSR2);
        printf("childn");
    }
}

当我执行我的程序时,我得到的只是:-

child
Segmentation fault (core dumped)

我是 C 语言系统调用的新手,不明白为什么会发生这种情况,以及如何获得所需的输出,即打印所有三个printf语句。任何帮助将不胜感激。

您的代码有许多小问题,并且肯定具有未定义的行为,即您不能从信号处理程序调用 printf 或其他异步信号不安全函数。这是带有修复的代码(请参阅代码中的注释)。这应该按预期工作(没有特定的打印语句顺序),并查看此代码是否仍然出现段错误。

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
void func1(int signum)
{
    /* write is asyc-signal-safe */
    write(1, "Received sig from childn", sizeof "Received sig from childn" - 1);
}
int main()
{
    signal(SIGUSR2, func1);
    /* fork returns a pid_t */
    pid_t c = fork();
    if(c > 0) {
        printf("parentn");
        /* Wait for the child to exit; otherwise, you may not receive the signal */
        if (wait(NULL) == -1) {
            printf("wait(2) failedn");
            exit(1);
        }
    } else if (c == -1) {
        printf("fork(2) errorn");
        exit(1);
    } else {
        if (kill(getppid(), SIGUSR2) == -1) {
            /* In case kill fails to send signal... */
            printf("kill(2) failedn");
            exit(1);
        }
        printf("childn");
    }
}

最新更新