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

来源:互联网 发布:销售网络建设与管理 编辑:程序博客网 时间:2024/05/22 17:14

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.
参考:https://stackoverflow.com/questions/32780706/does-linux-kill-background-processes-if-we-close-the-terminal-from-which-it-has


代码:

#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




阅读全文
0 0
原创粉丝点击