1. 程式人生 > >linux程序訊號處理函式signal和sigaction

linux程序訊號處理函式signal和sigaction

Linux中signal函式說明:

NAME
       signal - ANSI C signal handling


SYNOPSIS
       #include <signal.h>


       typedef void (*sighandler_t)(int);


       sighandler_t signal(int signum, sighandler_t handler);

DESCRIPTION
       The behavior of signal() varies across Unix versions, and has also var-
       ied historically across different versions of Linux.   Avoid  its  use:
       use sigaction(2) instead.  See Portability below.


       signal() sets the disposition of the signal signum to handler, which is
       either SIG_IGN, SIG_DFL, or the address of a  programmer-defined  func-
       tion (a "signal handler").


       If  the signal signum is delivered to the process, then one of the fol-
       lowing happens:


       *  If the disposition is set to SIG_IGN, then the signal is ignored.


       *  If the disposition is set to SIG_DFL, then the default action  asso-
          ciated with the signal (see signal(7)) occurs.


       *  If  the disposition is set to a function, then first either the dis-
          position is reset to SIG_DFL, or the signal is blocked  (see  Porta-
          bility  below), and then handler is called with argument signum.  If
          invocation of the handler caused the signal to be blocked, then  the
          signal is unblocked upon return from the handler.

       The signals SIGKILL and SIGSTOP cannot be caught or ignored.


RETURN VALUE
       signal()  returns  the previous value of the signal handler, or SIG_ERR
       on error.


ERRORS
       EINVAL signum is invalid.

使用示例:

 #include <signal.h>
 #include <stdio.h>
 #include <unistd.h>

 void ouch(int sig)
 {
     printf("I got signal %d\n", sig);
     // (void) signal(SIGINT, SIG_DFL);
     //(void) signal(SIGINT, ouch);
 
 }
 int main()
 {
     (void) signal(SIGINT, ouch);
     while(1)
     {
         printf("hello world...\n");
         sleep(1);
     }
 }
實際運用中,需要對不同到signal設定不同的到訊號處理函式,SIG_IGN忽略/SIG_DFL預設,這倆巨集也可以作為訊號處理函式。同時SIGSTOP/SIGKILL這倆訊號無法捕獲和忽略。注意,經過實驗發現,signal函式也會堵塞當前正在處理的signal,但是沒有辦法阻塞其它signal,比如正在處理SIG_INT,再來一個SIG_INT則會堵塞,但是來SIG_QUIT則會被其中斷,如果SIG_QUIT有處理,則需要等待SIG_QUIT處理完了,SIG_INT才會接著剛才處理。

Linux中sigaction函式說明:

NAME
       sigaction - examine and change a signal action


SYNOPSIS
       #include <signal.h>


       int sigaction(int signum, const struct sigaction *act,
                     struct sigaction *oldact);


   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):


       sigaction(): _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE


DESCRIPTION
       The  sigaction()  system  call  is used to change the action taken by a
       process on receipt  of  a  specific  signal.   (See  signal(7)  for  an
       overview of signals.)


       signum  specifies the signal and can be any valid signal except SIGKILL
       and SIGSTOP.

       If act is non-null, the new action for signal signum is installed  from
       act.  If oldact is non-null, the previous action is saved in oldact.


       The sigaction structure is defined as something like:


           struct sigaction {
               void     (*sa_handler)(int);
               void     (*sa_sigaction)(int, siginfo_t *, void *);
               sigset_t   sa_mask;
               int        sa_flags;
               void     (*sa_restorer)(void);
           };


       On  some  architectures  a  union  is  involved:  do not assign to both
       sa_handler and sa_sigaction.


       The sa_restorer element is obsolete and should not be used.  POSIX does
       not specify a sa_restorer element.

       sa_handler specifies the action to be associated with signum and may be
       SIG_DFL for the default action, SIG_IGN to ignore  this  signal,  or  a
       pointer to a signal handling function.  This function receives the sig-
       nal number as its only argument.


       If SA_SIGINFO is specified in sa_flags, then sa_sigaction  (instead  of
       sa_handler)  specifies  the  signal-handling function for signum.  This
       function receives the signal number as its first argument, a pointer to
       a  siginfo_t as its second argument and a pointer to a ucontext_t (cast
       to void *) as its third argument.


       sa_mask specifies a mask of signals  which  should  be  blocked  (i.e.,
       added  to  the signal mask of the thread in which the signal handler is
       invoked) during execution of the signal handler.  In addition, the sig-
       nal  which triggered the handler will be blocked, unless the SA_NODEFER
       flag is used.


       sa_flags specifies a set of flags which modify the behavior of the sig-
       nal.  It is formed by the bitwise OR of zero or more of the following:

           SA_NOCLDSTOP
                  If signum is SIGCHLD, do not receive notification when child
                  processes stop (i.e., when  they  receive  one  of  SIGSTOP,
                  SIGTSTP,  SIGTTIN  or SIGTTOU) or resume (i.e., they receive
                  SIGCONT) (see wait(2)).  This flag is only  meaningful  when
                  establishing a handler for SIGCHLD.


           SA_NOCLDWAIT (Since Linux 2.6)
                  If signum is SIGCHLD, do not transform children into zombies
                  when they terminate.  See also  waitpid(2).   This  flag  is
                  only  meaningful when establishing a handler for SIGCHLD, or
                  when setting that signal’s disposition to SIG_DFL.


                  If the SA_NOCLDWAIT flag is set when establishing a  handler
                  for SIGCHLD, POSIX.1 leaves it unspecified whether a SIGCHLD
                  signal is generated when a  child  process  terminates.   On
                  Linux,  a  SIGCHLD signal is generated in this case; on some
                  other implementations, it is not.

           SA_NODEFER
                  Do not prevent the signal from being  received  from  within
                  its  own  signal handler.  This flag is only meaningful when
                  establishing a signal handler.  SA_NOMASK  is  an  obsolete,
                  non-standard synonym for this flag.


           SA_ONSTACK
                  Call  the  signal  handler on an alternate signal stack pro-
                  vided by sigaltstack(2).   If  an  alternate  stack  is  not
                  available,  the  default  stack  will be used.  This flag is
                  only meaningful when establishing a signal handler.


           SA_RESETHAND
                  Restore the signal action to the default state once the sig-
                  nal  handler  has been called.  This flag is only meaningful
                  when establishing a signal handler.  SA_ONESHOT is an  obso-
                  lete, non-standard synonym for this flag.


           SA_RESTART
                  Provide  behavior  compatible  with  BSD signal semantics by
                  making certain  system  calls  restartable  across  signals.
                  This flag is only meaningful when establishing a signal han-
                  dler.   See  signal(7)  for  a  discussion  of  system  call
                  restarting.


           SA_SIGINFO (since Linux 2.2)
                  The  signal  handler  takes  3  arguments, not one.  In this
                  case, sa_sigaction should  be  set  instead  of  sa_handler.
                  This flag is only meaningful when establishing a signal han-
                  dler.

       The siginfo_t argument to sa_sigaction is a struct with  the  following
       elements:


           siginfo_t {
               int      si_signo;    /* Signal number */
               int      si_errno;    /* An errno value */
               int      si_code;     /* Signal code */
               int      si_trapno;   /* Trap number that caused
                                        hardware-generated signal
                                        (unused on most architectures) */
               pid_t    si_pid;      /* Sending process ID */
               uid_t    si_uid;      /* Real user ID of sending process */
               int      si_status;   /* Exit value or signal */
               clock_t  si_utime;    /* User time consumed */
               clock_t  si_stime;    /* System time consumed */
               sigval_t si_value;    /* Signal value */
               int      si_int;      /* POSIX.1b signal */
               void    *si_ptr;      /* POSIX.1b signal */
               int      si_overrun;  /* Timer overrun count; POSIX.1b timers */
               int      si_timerid;  /* Timer ID; POSIX.1b timers */
               void    *si_addr;     /* Memory location which caused fault */
               int      si_band;     /* Band event */

           }


       si_signo,  si_errno and si_code are defined for all signals.  (si_errno
       is generally unused on Linux.)  The rest of the struct may be a  union,
       so  that  one  should  only read the fields that are meaningful for the
       given signal:


       * POSIX.1b signals and SIGCHLD fill in si_pid and si_uid.


       * POSIX.1b timers (since Linux 2.6) fill in si_overrun and  si_timerid.
         The si_timerid field is an internal ID used by the kernel to identify
         the timer; it is not the same as the timer ID returned by  timer_cre-
         ate(2).


       * SIGCHLD  fills in si_status, si_utime and si_stime.  The si_utime and
         si_stime fields do not include the times used by waited for  children
         (unlike  getrusage(2)  and  time(2).  In kernels up to 2.6, and since
         2.6.27,   these   fields   report    CPU    time    in    units    of
         sysconf(_SC_CLK_TCK).  In 2.6 kernels before 2.6.27, a bug meant that
         these fields reported time in  units  of  the  (configurable)  system
         jiffy (see time(7)).

       * si_int and si_ptr are specified by the sender of the POSIX.1b signal.
         See sigqueue(2) for more details.


       * SIGILL, SIGFPE, SIGSEGV, and SIGBUS fill in si_addr with the  address
         of the fault.  SIGPOLL fills in si_band and si_fd.


       si_code  is  a  value  (not  a bit mask) indicating why this signal was
       sent.  The following list shows the  values  which  can  be  placed  in
       si_code  for  any  signal, along with reason that the signal was gener-
       ated.


           SI_USER        kill(2) or raise(3)


           SI_KERNEL      Sent by the kernel.


           SI_QUEUE       sigqueue(2)


           SI_TIMER       POSIX timer expired


           SI_MESGQ       POSIX  message  queue  state  changed  (since  Linux
                          2.6.6); see mq_notify(3)

           SI_ASYNCIO     AIO completed


           SI_SIGIO       queued SIGIO


           SI_TKILL       tkill(2) or tgkill(2) (since Linux 2.4.19)


       The following values can be placed in si_code for a SIGILL signal:


           ILL_ILLOPC     illegal opcode


           ILL_ILLOPN     illegal operand


           ILL_ILLADR     illegal addressing mode


           ILL_ILLTRP     illegal trap


           ILL_PRVOPC     privileged opcode


           ILL_PRVREG     privileged register


           ILL_COPROC     coprocessor error

           ILL_BADSTK     internal stack error


       The following values can be placed in si_code for a SIGFPE signal:


           FPE_INTDIV     integer divide by zero


           FPE_INTOVF     integer overflow


           FPE_FLTDIV     floating-point divide by zero


           FPE_FLTOVF     floating-point overflow


           FPE_FLTUND     floating-point underflow


           FPE_FLTRES     floating-point inexact result


           FPE_FLTINV     floating-point invalid operation


           FPE_FLTSUB     subscript out of range


       The following values can be placed in si_code for a SIGSEGV signal:


           SEGV_MAPERR    address not mapped to object

           SEGV_ACCERR    invalid permissions for mapped object


       The following values can be placed in si_code for a SIGBUS signal:


           BUS_ADRALN     invalid address alignment


           BUS_ADRERR     nonexistent physical address


           BUS_OBJERR     object-specific hardware error


       The following values can be placed in si_code for a SIGTRAP signal:


           TRAP_BRKPT     process breakpoint


           TRAP_TRACE     process trace trap


       The following values can be placed in si_code for a SIGCHLD signal:


           CLD_EXITED     child has exited

           CLD_KILLED     child was killed


           CLD_DUMPED     child terminated abnormally


           CLD_TRAPPED    traced child has trapped


           CLD_STOPPED    child has stopped


           CLD_CONTINUED  stopped child has continued (since Linux 2.6.9)


       The following values can be placed in si_code for a SIGPOLL signal:


           POLL_IN        data input available


           POLL_OUT       output buffers available


           POLL_MSG       input message available


           POLL_ERR       i/o error


           POLL_PRI       high priority input available


           POLL_HUP       device disconnected

RETURN VALUE
       sigaction() returns 0 on success and -1 on error.


ERRORS
       EFAULT act  or oldact points to memory which is not a valid part of the
              process address space.


       EINVAL An invalid signal was specified.  This will also be generated if
              an  attempt is made to change the action for SIGKILL or SIGSTOP,
              which cannot be caught or ignored.

使用示例:

#include <signal.h>
#include <stdio.h>
#include <unistd.h>

void ouch(int sig)
{
    printf("oh, got a signal %d\n", sig);

    int i = 0;
    for (i = 0; i < 5; i++)
    {
        printf("signal func %d\n", i);
        sleep(1);
    }
}


int main()
{
    struct sigaction act;
    act.sa_handler = ouch;
    sigemptyset(&act.sa_mask);
    sigaddset(&act.sa_mask, SIGQUIT);
    // act.sa_flags = SA_RESETHAND;
    // act.sa_flags = SA_NODEFER;
    act.sa_flags = 0;
 
    sigaction(SIGINT, &act, 0);
    struct sigaction act_2;
    act_2.sa_handler = ouch;
    sigemptyset(&act_2.sa_mask);
    act.sa_flags = 0;
    sigaction(SIGQUIT, &act_2, 0);
    while(1)
    {
         sleep(1);
    }
    return;
}

1. 阻塞,sigaction函式有阻塞的功能,比如SIGINT訊號來了,進入訊號處理函式,預設情況下,在訊號處理函式未完成之前,如果又來了一個SIGINT訊號,其將被阻塞,只有訊號處理函式處理完畢,才會對後來的SIGINT再進行處理,同時後續無論來多少個SIGINT,僅處理一個SIGINT,sigaction會對後續SIGINT進行排隊合併處理。

2. sa_mask,訊號遮蔽集,可以通過函式sigemptyset/sigaddset等來清空和增加需要遮蔽的訊號,上面程式碼中,對訊號SIGINT處理時,如果來訊號SIGQUIT,其將被遮蔽,但是如果在處理SIGQUIT,來了SIGINT,則首先處理SIGINT,然後接著處理SIGQUIT。

3. sa_flags如果取值為0,則表示預設行為。還可以取如下倆值,但是我沒覺得這倆值有啥用。

SA_NODEFER,如果設定來該標誌,則不進行當前處理訊號到阻塞

SA_RESETHAND,如果設定來該標誌,則處理完當前訊號後,將訊號處理函式設定為SIG_DFL行為