我正在使用 waitpid(2) 检查和标记作业控制程序的进程状态。我正在使用 WUNTRACED 选项,以在作业控制程序中捕获有用的信号,如 SIGTSTP。
问题是,当 CTRL-Z (SIGTSTP) 我的程序时,waitpid(2) 返回的 PID 是正确的 (>0),但是当用 CTRL-C (SIGINT) 终止它时,返回的 PID 是 - 1.那个怎么样 ?那么我怎样才能标记我的进程的状态呢?因为它返回一个无效的 PID 并将 errno 设置为 ECHILD。
#include <sys/types.h>
#include <stdbool.h>
#include <termios.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
int main(void)
{
pid_t pid;
pid_t ret;
int stat_loc;
if ((!(pid = fork())))
{
execve("/bin/ls", (char *const []){"ls", "-Rl", "/", NULL}, NULL);
}
else if (pid > 0)
{
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
signal(SIGTSTP, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
signal(SIGCHLD, SIG_IGN);
ret = waitpid(-1, &stat_loc, WUNTRACED);
printf("\nwaitpid returned %d\n", ret);
}
return (0);
}
编辑:问题已解决,请在忽略它时使用 SIGCHLD 查看技巧。
最佳答案
你忽略了 SIGCHLD
:
signal(SIGCHLD, SIG_IGN);
Status information for a process shall be generated (made available to the parent process) when the process stops, continues, or terminates except in the following case:
- If the parent process sets the action for the
SIGCHLD
signal toSIG_IGN
, or if the parent sets theSA_NOCLDWAIT
flag for theSIGCHLD
signal action, process termination shall not generate new status information but shall cause any existing status information for the process to be discarded.
如果你想在子进程上wait()
,你不能忽略SIGCHLD
。
关于c - waitpid 的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49759112/