gpt4 book ai didi

c - 如何通过kill命令从子进程向父进程发送信号

转载 作者:行者123 更新时间:2023-11-30 14:43:13 24 4
gpt4 key购买 nike

我试图通过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 child\n");
}
}

int main() {
signal(SIGUSR2, func1);

int c = fork();
if(c > 0) {
printf("parent\n");
}
else if(c == -1) {
printf("No child");
}
else {
kill(getppid(), SIGUSR2);
printf("child\n");
}

}

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

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 child\n", sizeof "Received sig from child\n" - 1);
}

int main()
{
signal(SIGUSR2, func1);

/* fork returns a pid_t */
pid_t c = fork();
if(c > 0) {
printf("parent\n");
/* Wait for the child to exit; otherwise, you may not receive the signal */
if (wait(NULL) == -1) {
printf("wait(2) failed\n");
exit(1);
}
} else if (c == -1) {
printf("fork(2) error\n");
exit(1);
} else {
if (kill(getppid(), SIGUSR2) == -1) {
/* In case kill fails to send signal... */
printf("kill(2) failed\n");
exit(1);
}
printf("child\n");
}
}

关于c - 如何通过kill命令从子进程向父进程发送信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54076914/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com