控制进程结束的时候,后台进程信号处理

Kernel sends SIGHUP to controlling process:

  • for real (hardware) terminal: when disconnect is detected in a terminal driver, e.g. on hang-up on modem line;
  • for pseudoterminal (pty): when last descriptor referencing master side of pty is closed, e.g. when you close terminal window.

Kernel sends SIGHUP to other process groups:

  • to foreground process group, when controlling process terminates;
  • to orphaned process group, when it becomes orphaned and it has stopped members.


代码:

#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);
  }


执行结果果然是先接收到SIGCONT然后才是SIGHUP信号,虽然按照APUE书上说是先发送的SIGHUP信号然后是SIGCONT信号, 先发送的SIGHUP反而后面收到的
,后面发送SIGCONT先收到了

解释:

The SIGHUP cannot be delivered until the child's execution is resumed. When a process is stopped, all signal delivery is suspended except for SIGCONT and SIGKILL.

So, the SIGHUP does arrive first, but it cannot be processed until the SIGCONT awakens the process execution.

参考: https://stackoverflow.com/questions/17768459/order-of-sigcont-and-sighup-sent-to-orphaned-linux-process-group




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值