Return waitpid 的值

Return value of waitpid

我正在使用 waitpid(2) 检查和标记作业控制程序的进程状态。我正在使用 WUNTRACED 选项,以在作业控制程序中捕获有用的信号,如 SIGTSTP。

问题是,当 CTRL-Z (SIGTSTP) 我的程序时,waitpid(2) 编辑的 PID return 是正确的 (>0),但是当用 CTRL-C (SIGINT) 杀死它时),PID returned 为 -1。那个怎么样 ?那么我怎样才能标记我的进程的状态呢?因为它 return 一个无效的 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);

Per POSIX:

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 to SIG_IGN, or if the parent sets the SA_NOCLDWAIT flag for the SIGCHLD 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