c - SIGCONT 和 SIGHUP 命令发送到孤立的 linux 进程组

标签 c linux unix process signals

APUE 说

Since the process group is orphaned when the parentterminates, POSIX.1 requires that every process in the newly orphaned process group that is stopped (as our child is) be sent the hang-up signal (SIGHUP) followed by the continue signal (SIGCONT)

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#define errexit(msg) do{ perror(msg); exit(EXIT_FAILURE); } while(0)
static void sig_hup(int signo)
{
    printf("SIGHUP received, pid = %d\n", getpid());
}
static void sig_cont(int signo)
{
    printf("SIGCONT received, pid = %d\n", getpid());
}
static void sig_ttin(int signo)
{
    printf("SIGTTIN received, pid = %d\n", getpid());
}
static void pr_ids(char *name)
{
    printf("%s: pid = %d, ppid = %d, pgrp = %d, tpgrp = %d\n",
           name, getpid(), getppid(), getpgrp(), tcgetpgrp(STDIN_FILENO));
}
int main(int argc, char *argv[])
{
    char c;
    pid_t pid;
    setbuf(stdout, NULL);
    pr_ids("parent");
    if ((pid = fork()) < 0) {
            errexit("fork error");
    } else if (pid > 0) { /* parent */
            sleep(5);
            printf("parent exit\n");
            exit(0);
    } else { /* child */
            pr_ids("child...1");
            signal(SIGCONT, sig_cont);
            signal(SIGHUP, sig_hup);
            signal(SIGTTIN, sig_ttin);
            kill(getpid(), SIGTSTP);
            //sleep(10);
            pr_ids("child...2");
            if (read(STDIN_FILENO, &c, 1) != 1) {
                    printf("read error from controlling TTY, errno = %d\n", 
                                                             errno);
            }
            printf("child exit\n");
    }
    exit(0);
  }

程序输出:

parent: pid = 2036, ppid = 1959, pgrp = 2036, tpgrp = 2036
child...1: pid = 2037, ppid = 2036, pgrp = 2036, tpgrp = 2036
parent exit
xiejingfeng@xiejingfeng-desktop:/codes/apue$ SIGCONT received, pid = 2037
SIGHUP received, pid = 2037
child...2: pid = 2037, ppid = 1, pgrp = 2036, tpgrp = 1959
read error from controlling TTY, errno = 5
child exit

输出并不像书上说的那样,因为程序首先接收到 SIGCONT 然后是 SIGHUP,这让我很困惑,你们能帮帮我吗?

提前致谢。

最佳答案

SIGHUP 在 child 的执行恢复之前无法传递。当进程停止时,除了 SIGCONTSIGKILL 之外的所有信号传递都将暂停。

因此,SIGHUP确实先到了,但是直到SIGCONT唤醒进程执行后才能处理。

关于c - SIGCONT 和 SIGHUP 命令发送到孤立的 linux 进程组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17768459/

相关文章:

c++ - 间隔树 - 主要功能障碍的功能

c - 分配器的 LLVM/Clang 特例

linux - 如何列出 USB 端口类型和连接设备的速度?

unix - 在 AWK 中为多个文件更改 FS

linux - 如何将带引号的字符串作为参数传递给 bash 中的函数?

java - 如何在没有关联窗口的情况下使图像出现在屏幕上

php - C/PHP 中的复合 bool 表达式和变量赋值

regex - 使用正则表达式通过 Bash 检查范围

c++ - 是否可以将 gcc 的链接器与 dlopen 结合使用?

c - 如何在 Unix 网络编程中使用 header