自己写函数处理SIGTSTP信号

来源:互联网 发布:2017千百网址最新域名 编辑:程序博客网 时间:2024/05/12 09:12

只有在当前shell(echo $SHELL)不忽略SIGTSTP信号时,才去调用自己写的handler。

/bin/sh不支持。

因为init进程三个进程控制信号SIGTSTP,SIGTTIN,SIGTTOU设置为SIG_IGN,支持者三个进程控制的shell重新设置为SIG_DFL.


源代码:

cat -n 10_31.c
     1  #include "apue.h"
     2
     3  #define BUFSIZE 1024
     4
     5  void sig_stop(int signo)
     6  {
     7          //move cursor to left bottom;
     8          //redraw the screen;
     9
    10          sigset_t mask;
    11          sigemptyset(&mask);
    12          sigaddset(&mask,SIGTSTP);
    13          sigprocmask(SIG_UNBLOCK,&mask,NULL);
    14
    15
    16
    17          //reset to original SIGTSTP handler;
    18          signal(SIGTSTP,SIG_DFL);
    19
    20          kill(getpid(),SIGTSTP);
    21
    22          //we will not return from kill until we are continuted.
    23
    24          //redraw the screen.
    25
    26          signal(SIGTSTP,sig_stop);
    27
    28  }
    29
    30
    31
    32  int main()
    33  {
    34          char buf[BUFSIZE];
    35          int n;
    36
    37          //We handle SIGTSTP only when system doesn't ingore it.
    38          if (signal(SIGTSTP,SIG_IGN) == SIG_DFL){
    39                  signal(SIGTSTP,sig_stop);
    40                  printf("establish sig_stop success\n");
    41          }
    42          while ((n = read(STDIN_FILENO,buf,BUFSIZE)) > 0){
    43                  if (write(STDOUT_FILENO,buf,n) != n)
    44                          err_sys("write error");
    45          }
    46
    47
    48          if (n < 0)
    49                  err_sys("read error");
    50
    51          return 0;
    52  }



执行结果:

/handle_SIGTSTP
establish sig_stop success
hello
hello
^Z
[1]+  Stopped                 ./handle_SIGTSTP
<bldc:/home/tingbinz/apue.3e/SBSCODE/10>\R*_*G:fg
./handle_SIGTSTP
world
world
^C
<bldc:/home/tingbinz/apue.3e/SBSCODE/10>\R*_*G:

0 0
原创粉丝点击