【发布时间】:2023-04-11 10:06:01
【问题描述】:
我的目标:我有一个简单的 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);
}
【问题讨论】:
-
您确定要发送 SIGTSTP(即 control + Z ,而不是 control + C)。对于孩子和父母来说,处理程序是相同的。在我的系统上运行良好。
-
乍一看,我看不出拨打
setpgid的原因[他们可能对您遇到的困难负责]。您可能想在父/子中做不同的事情。家长:signal(SIGTSTP,SIG_IGN)。孩子:signal(SIGTSTP,SIGTSTP_Handler)另外,让SIGTSTP_Handler给自己发送一个信号也无济于事,因为它只有在信号已经从外部发送到进程时才会被调用(例如,孩子收到信号然后发送 same 向自身发出信号)。 -
感谢您的快速回复!我为父级设置了处理程序,以便我可以捕获
SIGTSTP并将其重定向到子级。我想我也可以将signal(SIGTSTP, SIG_IGN)添加到父级,而对子级的信号处理不做任何事情。我认为问题可能是我使用 make 命令运行我的代码,因为当我的程序停止时我看到以下内容:[2]+ Stopped make