gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:39:25 32 4
gpt4 key购买 nike

APUE 说

Since the process group is orphaned when the parentterminates, POSIX.1 requires that every process inthe 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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com