c - waitpid 的返回值

标签 c linux unix system wait

我正在使用 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);

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

关于c - waitpid 的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49759112/

相关文章:

linux - 如何将所有具有相同后缀的文件复制到另一个目录? - Unix

命令行参数不起作用 C

c - 当前的 C 标准是否禁止将 `&` 和 `|` 短路?

linux - 转换-追加*网格

linux - 我如何使用 ioctl() 来操作我的内核模块?

linux - Snort 和 Iptables 与 Linux 内核的交互

c - 生产者消费者问题:posix mutex got locked twice when using condition variable?

c - typedef with function this 被问到但无法理解?

c - 与 c 相比,Go 的二进制大小

C - 如何为结构内的链表分配内存