Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4027295
  • 博文数量: 366
  • 博客积分: 9916
  • 博客等级: 中将
  • 技术积分: 7195
  • 用 户 组: 普通用户
  • 注册时间: 2011-05-29 23:27
个人简介

简单!

文章分类

全部博文(366)

文章存档

2013年(51)

2012年(269)

2011年(46)

分类: LINUX

2011-06-06 14:06:05

                               sigaction的使用
 
sigaction的原型如下:
int sigaction ( int signo, const struct sigaction * restrict act,

              struct sigaction * restrict oact) ;
 
SIGACTION(2) -- 2010-06-16 -- Linux -- Linux Programmer's Manual

NAME
     sigaction - examine and change a signal action

SYNOPSIS
     #include

     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  signal  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  signal  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  signal.  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, nonstandard  synonym for
              this flag.

         SA_ONSTACK
              Call  the  signal handler  on  an alternate  signal
              stack provided 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 signal  handler has been called.   This flag is
              only meaningful when establishing a signal handler.
              SA_ONESHOT is an  obsolete, nonstandard 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 handler.  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 handler.

     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 */
             long     si_band;     /* Band event (was int in
                                      glibc 2.3.2 and earlier) */
             int      si_fd;       /* File descriptor */
             short    si_addr_lsb; /* Least significant bit of address
                                      (since kernel 2.6.32) */
         }

     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:

     * Signals sent  with kill(2) and sigqueue(2)  fill in si_pid
       and  si_uid.  In addition,  signals sent  with sigqueue(2)
       fill in si_int and si_ptr with the values specified by the
       sender the signal; see sigqueue(2) for more details.

     * Signals sent by 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_create(2).   The  si_overrun   field  is  the  timer
       overrun count; this is the same information as is obtained
       by  a  call  to  timer_getoverrun(2).   These  fields  are
       nonstandard Linux extensions.

     * Signals  sent  for  message  queue notification  (see  the
       description  of  SIGEV_SIGNAL  in  mq_notify(3))  fill  in
       si_int/si_ptr,   with    the   sigev_value   supplied   to
       mq_notify(3); si_pid,  with the process ID  of the message
       sender; and si_uid,  with the real user ID  of the message
       sender.

     * SIGCHLD fills  in si_pid, si_uid,  si_status, si_utime and
       si_stime,  providing  information  about the  child.   The
       si_pid field is the process ID of the child; si_uid is the
       child's real  user ID.   The si_status field  contains the
       exit status  of the child  (if si_code is  CLD_EXITED), or
       the signal number that caused the process to change state.
       The si_utime and si_stime  contain the user and system CPU
       time  used  by the  child  process;  these  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)).

     * SIGILL,  SIGFPE,  SIGSEGV,  SIGBUS,  and SIGTRAP  fill  in
       si_addr  with   the  address   of  the  fault.    On  some
       architectures,  these signals also  fill in  the si_trapno
       filed.    Some   suberrors   of  SIGBUS,   in   particular
       BUS_MCEERR_AO and BUS_MCEERR_AR, also fill in si_addr_lsb.
       This  field indicates  the  least significant  bit of  the
       reported   address  and  therefore   the  extent   of  the
       corruption.  For  example, if  a full page  was corrupted,
       si_addr_lsb      contains     log2(sysconf(_SC_PAGESIZE)).
       BUS_MCERR_* and si_addr_lsb are Linux-specific extensions.

     * SIGPOLL/SIGIO  fills in  si_band and  si_fd.   The si_band
       event  is a  bit mask  containing the  same values  as are
       filled in  the revents field by poll(2).   The si_fd field
       indicates  the file  descriptor  for which  the I/O  event
       occurred.

     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 generated.

         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

         BUS_MCEERR_AR (since Linux 2.6.32)
                        Hardware  memory   error  consumed  on  a
                        machine check; action required.

         BUS_MCEERR_AO (since Linux 2.6.32)
                        Hardware memory error detected in process
                        but not consumed; action optional.

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

         TRAP_BRKPT     process breakpoint

         TRAP_TRACE     process trace trap

         TRAP_BRANCH (since Linux 2.4)
                        process taken branch trap

         TRAP_HWBKPT (since Linux 2.4)
                        hardware breakpoint/watchpoint

     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.

CONFORMING TO
     POSIX.1-2001, SVr4.

NOTES
     A child created via fork(2)  inherits a copy of its parent's
     signal dispositions.  During  an execve(2), the dispositions
     of   handled  signals   are  reset   to  the   default;  the
     dispositions of ignored signals are left unchanged.

     According to  POSIX, the behavior of a  process is undefined
     after it  ignores a SIGFPE,  SIGILL, or SIGSEGV  signal that
     was not generated by  kill(2) or raise(3).  Integer division
     by zero has undefined result.  On some architectures it will
     generate a SIGFPE signal.   (Also dividing the most negative
     integer by  -1 may  generate SIGFPE.)  Ignoring  this signal
     might lead to an endless loop.

     POSIX.1-1990  disallowed setting the  action for  SIGCHLD to
     SIG_IGN.   POSIX.1-2001  allows  this possibility,  so  that
     ignoring  SIGCHLD can  be used  to prevent  the  creation of
     zombies (see wait(2)).  Nevertheless, the historical BSD and
     System V behaviors for  ignoring SIGCHLD differ, so that the
     only completely portable  method of ensuring that terminated
     children  do not  become  zombies is  to  catch the  SIGCHLD
     signal and perform a wait(2) or similar.

     POSIX.1-1990  only   specified  SA_NOCLDSTOP.   POSIX.1-2001
     added    SA_NOCLDWAIT,    SA_RESETHAND,   SA_NODEFER,    and
     SA_SIGINFO.  Use  of these latter values in  sa_flags may be
     less  portable  in  applications  intended  for  older  Unix
     implementations.

     The SA_RESETHAND  flag is compatible  with the SVr4  flag of
     the same name.

     The SA_NODEFER flag is compatible  with the SVr4 flag of the
     same name  under kernels 1.3.9 and newer.   On older kernels
     the Linux implementation allowed  the receipt of any signal,
     not just  the one we are  installing (effectively overriding
     any sa_mask settings).

     sigaction()  can be called  with a  NULL second  argument to
     query the  current signal handler.   It can also be  used to
     check  whether  a given  signal  is  valid  for the  current
     machine by calling it with NULL second and third arguments.

     It  is  not  possible   to  block  SIGKILL  or  SIGSTOP  (by
     specifying them in sa_mask).  Attempts to do so are silently
     ignored.

     See sigsetops(3) for details on manipulating signal sets.

     See signal(7) for a  list of the async-signal-safe functions
     that  can  be safely  called  inside  from  inside a  signal
     handler.

   Undocumented
     Before the  introduction of SA_SIGINFO it  was also possible
     to  get  some  additional  information, namely  by  using  a
     sa_handler with  second argument of  type struct sigcontext.
     See the  relevant kernel sources  for details.  This  use is
     obsolete now.

BUGS
     In kernels up to and including 2.6.13, specifying SA_NODEFER
     in  sa_flags prevents  not  only the  delivered signal  from
     being masked  during execution of the handler,  but also the
     signals specified in sa_mask.   This bug was fixed in kernel
     2.6.14.

EXAMPLE
     See mprotect(2).


SEE ALSO
     kill(1),   kill(2),  killpg(2),   pause(2),  sigaltstack(2),
     signal(2),   signalfd(2),   sigpending(2),   sigprocmask(2),
     sigqueue(2),      sigsuspend(2),      wait(2),     raise(3),
     siginterrupt(3), sigsetops(3), sigvec(3), core(5), signal(7)

COLOPHON
     This page  is part  of release 3.28  of the  Linux man-pages
     project.   A  description of  the  project, and  information
     about     reporting     bugs,     can    be     found     at
     



MPROTECT(2) -- 2008-08-06 -- Linux -- Linux Programmer's Manual

NAME
     mprotect - set protection on a region of memory

SYNOPSIS
     #include

     int mprotect(const void *addr, size_t len, int prot);

DESCRIPTION
     mprotect()  changes  protection  for the  calling  process's
     memory page(s)  containing any part of the  address range in
     the interval [addr, addr+len-1].  addr  must be aligned to a
     page boundary.

     If the  calling process tries  to access memory in  a manner
     that violates  the protection,  then the kernel  generates a
     SIGSEGV signal for the process.

     prot is either PROT_NONE or a bitwise-or of the other values
     in the following list:

     PROT_NONE  The memory cannot be accessed at all.

     PROT_READ  The memory can be read.

     PROT_WRITE The memory can be modified.

     PROT_EXEC  The memory can be executed.

RETURN VALUE
     On  success,  mprotect()  returns  zero.  On  error,  -1  is
     returned, and errno is set appropriately.

ERRORS

     EACCES
          The memory cannot be  given the specified access.  This
          can happen, for example, if you mmap(2) a file to which
          you have read-only access,  then ask mprotect() to mark
          it PROT_WRITE.

     EINVAL
          addr is not  a valid pointer, or not  a multiple of the
          system page size.

     ENOMEM
          Internal kernel structures could not be allocated.

     ENOMEM
          Addresses in the range [addr, addr+len] are invalid for
          the  address space of  the process,  or specify  one or
          more pages that are not mapped.  (Before kernel 2.4.19,
          the  error EFAULT  was incorrectly  produced  for these
          cases.)

CONFORMING TO
     SVr4,  POSIX.1-2001.   POSIX   says  that  the  behavior  of
     mprotect() is  unspecified if it  is applied to a  region of
     memory that was not obtained via mmap(2).

NOTES
     On Linux it is always  permissible to call mprotect() on any
     address in a process's  address space (except for the kernel
     vsyscall  area).  In  particular it  can be  used  to change
     existing code mappings to be writable.

     Whether PROT_EXEC has any effect different from PROT_READ is
     architecture-   and  kernel   version-dependent.    On  some
     hardware  architectures  (e.g.,  i386),  PROT_WRITE  implies
     PROT_READ.

     POSIX.1-2001 says  that an implementation  may permit access
     other than that specified in prot, but at a minimum can only
     allow write access if PROT_WRITE  has been set, and must not
     allow any access if PROT_NONE has been set.

EXAMPLE

     The program below allocates  four pages of memory, makes the
     third  of these pages  read-only, and  then executes  a loop
     that  walks upward  through the  allocated  region modifying
     bytes.

     An example of what we  might see when running the program is
     the following:

         $ ./a.out
         Start of region:        0x804c000
         Got SIGSEGV at address: 0x804e000

   Program source
     #include
     #include
     #include
     #include
     #include
     #include
     #include

     #define handle_error(msg) \
         do { perror(msg); exit(EXIT_FAILURE); } while (0)

     char *buffer;

     static void
     handler(int sig, siginfo_t *si, void *unused)
     {
         printf("Got SIGSEGV at address: 0x%lx\n",
                 (long) si->si_addr);
         exit(EXIT_FAILURE);
     }

     int
     main(int argc, char *argv[])
     {
         char *p;
         int pagesize;
         struct sigaction sa;

         sa.sa_flags = SA_SIGINFO;
         sigemptyset(&sa.sa_mask);
         sa.sa_sigaction = handler;
         if (sigaction(SIGSEGV, &sa, NULL) == -1)
             handle_error("sigaction");

         pagesize = sysconf(_SC_PAGE_SIZE);
         if (pagesize == -1)
             handle_error("sysconf");

         /* Allocate a buffer aligned on a page boundary;
            initial protection is PROT_READ | PROT_WRITE */

         buffer = memalign(pagesize, 4 * pagesize);
         if (buffer == NULL)
             handle_error("memalign");

         printf("Start of region:        0x%lx\n", (long) buffer);

         if (mprotect(buffer + pagesize * 2, pagesize,
                     PROT_NONE) == -1)
             handle_error("mprotect");

         for (p = buffer ; ; )
             *(p++) = 'a';

         printf("Loop completed\n");     /* Should never happen */
         exit(EXIT_SUCCESS);
     }

SEE ALSO
     mmap(2), sysconf(3)

COLOPHON
     This page  is part  of release 3.28  of the  Linux man-pages
     project.   A  description of  the  project, and  information
     about     reporting     bugs,     can    be     found     at
     
 
 
把以上的具体实例运行调试一下就知道其用法了!
阅读(5377) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~