gpt4 book ai didi

c - SIGTSTP 处理程序终止父进程和子进程

转载 作者:太空狗 更新时间:2023-10-29 12:39:30 24 4
gpt4 key购买 nike

我的目标:我有一个简单的 c 程序,它应该用我自己的覆盖默认的 SIGTSTP 处理程序,并且只向子进程发送 SIGTSTP。

我的问题:SIGTSTP 处理程序中的 kill 调用会停止父进程,并退出我的程序(不仅仅是子进程)。我做错了什么?

编辑: 这个问题似乎只有在我使用以下 make 命令编译和运行代码时才会发生:gcc -o program *.c -lreadline && ./program。似乎(make 过程?)已终止,因为我的输出包含 ctrl-z 时的以下行:gcc -o sandbox *.c -lreadline && ./sandbox有没有办法既让我的程序具有所需的功能又使用 make?

我的代码:

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

int child;

void handler();

static void SIGTSTP_Handler()
{
if (child != 0) {
kill(child, SIGTSTP);
}
}

int main(void)
{
signal(SIGTSTP, SIGTSTP_Handler);

child = fork();

if (child == 0) {
setpgid(0, getpid());

printf("CHILD's PID ::: [ %d ]\n", getpid());

printf("CHILD's GROUP ::: %d\n", getpgrp());

execlp("sleep", "sleep", "30", NULL);

}
else {
setpgid(child, child);

int status;

printf("CHILD's PID (From Parent Perspective) ::: [ %d ]\n", child);

printf("PARENT's PID ::: %d\n", getpid());

printf("PARENT's GROUP ::: %d\n", getpgrp());

waitpid(child, &status, WUNTRACED | WCONTINUED);
}

while (1);
}

最佳答案

这个问题是因为我启动程序时使用的 make 命令被 ctrl-z 终止了。要解决此问题,您可以:

老有问题的 Make 命令:

gcc -o program *.c && ./program

可能的解决方案:

(1) 从 make 命令中删除 && ./program

(2) 在不使用 make 的情况下编译并运行你的程序

如果您希望在 SIGTSTP 信号的情况下保持主程序运行,我不确定是否仍然可以使用 make 启动程序

关于c - SIGTSTP 处理程序终止父进程和子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52394094/

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