Linux signals

Document Sample
Linux signals Powered By Docstoc
					Signals
                              Signals
• Signals
   – Used to report the occurrence of an event
   – An event can cause (generate or raise) a signal

                            Source of Signals




      Errors                External Events            Explicit Request




                            Timing of Signals




    Synchronous                                        Asynchronous
                        Signals
• Source of signals
  – Errors
     • An invalid operation of the program, that cannot be
       reported back in synchronous manner
     • Example : Divide by Zero, Invalid memory address
       access
  – External Event
     • Could be from I/O operation getting completed, a timer
       expiration, termination of child process
  – Explicit Request
     • A request by using the kill function to generate a signal
                          Signals
• Generation of signals
  – Synchronous Signals
     •   Caused by a specific action of the program
     •   Delivered during that action (unless it is blocked)
     •   Most errors generate signals synchronously
     •   Explicit request by a process to generate a signal to the
         same process is also usually synchronous
  – Asynchronous Signals
     • Generated by events outside of the control of the
       process that receives them
     • Arrive at unpredictable times during the execution of
       the program
                     Signals
• Signal Delivery
  – Once a signal is generated it is marked as pending
  – It then gets delivered to the process. Normally
    there is very little time difference between
    pending and delivery of the signal
  – It could remain in pending state if the process has
    blocked the signal, remain so till the signal is
    unblocked
  – On delivery, the specified function is invoked to
    perform the signal specific handling
  – The programmer can install their own signal
    handler or accept the default handling
                       Signals
• Signal Delivery
  – If the specified action for a signal is to ignore it,
    then the signal is discarded immediately after
    generation
     • Happens even if the signal is marked as blocked
  – Default action for signals are
     • Terminate the process
     • Terminate the process with generation of core file
     • Ignore the signal
  – If a process is terminated due to signal, its parent
    process can know this from the wait status
                        Signals
• Installing Signal Handler
  – Indicated by an integer number
  – Have a corresponding SIGXXXX macro, which
    should be used
  – Most signal names are standard across most
    systems
  – Installing Signal Handler
     • Use the function sigaction to install a new handler
  – sigaction
     • int sigaction (int signum, struct sigaction *new, struct
       sigaction *old)
                           Signals
• Installing Signal handlers
  – parameters
     • ‘new’ : Specifies the new handler to install and the
       associated parameters
     • ‘old’ : Location to retrieve the old handler
     • ‘new’ or ‘old’ can be NULL, and both can be non-null
  – struct sigaction members
     • sa_handler
        – Specifies the function to be installed for handling this signal
     • sa_mask
        – Specifies the set of signals to be masked while this handler
          runs
        – By default the signal that is delivered is automatically masked
                          Signals
• Installing Signal Handler
  – struct sigaction members
     • sa_flags
        – SA_NOCLDSTOP
            » Meant for SIGCHLD Signal. Delivers the signal only for
              child process termination and not for stopping. By default
              delivered for both
        – SA_ONSTACK
            » System uses the signal stack when delivering this signal
            » If no signal stack is set, then the process terminates with
              signal SIGILL
        – SA_RESTART
            » System calls like open, read, write which are interrupted
              by a signal can resume or return an error (EINTR)
            » With this flag, they will be resumed
                          Signals
• Installing a Signal Handler
  – struct sigaction members
     • sa_flags
        – SA_ONESHOT
            » Restore the signal to the default handler once the signal
              handler function is called
        – SA_NOMASK
            » Do not block the signal from its own signal handler
        – SA_SIGINFO
            » The signal handler function is new style
            » Accepts three arguments and not one
                           Signals
• Installing Signal Handler
  – Signal handler function prototype
     • void (int)
         – Obsolete used along with the function ‘signal’
     • void (int signum, siginfo_t *info, void *arg)
         – Signum
              » The signal that is being delivered
         – info
              » Gives more information about the signal and its
                environment
              » Details depend on the type of signal delivered
         – arg
              » User specified argument that is passed for certain signals
                         Signals
• Blocking and Unblocking Signals
  – Signals can be blocked
     • Sections of code, where we do not want to be
       interrupted
     • Can block a set of signals using the sigprocmask
     • If signal is raised when it is blocked the signal is kept
       pending
     • When the process unblocks the signal then it is
       delivered
     • See sigprocmask and pthread_sigmask for
       blocking/unblocking signals
                       Signals
• Generating Signals
  – Signals can be delivered to a process, a set of
    process
  – The kill system call can be used to generate a
    signal to a process
  – The pthread_kill can be used to generate a signal
    to a specified thread within a process
     • pthread_kill can only be used within a process to send
       signals to threads of the same process
                         Signals
• Restrictions in Signal handlers
  – Function runs in asynchronous mode
  – Should not take too long to complete, since then
    other normal routines may get affected
  – Is restricted on calls to functions
  – Should not call functions which can potentially
    block
     • Lock/mutex acquire, read/write on blocking file
       descriptors etc.
        – These can lead to potential dead locks
                          Signals
• Restrictions in Signal Handlers
  – Should only call functions which are async_safe
    (see Solaris man page – attributes at the bottom)
     • Similar thing not very clear on Linux
  – Communication with rest of the code
     • Setting global variables
     • Signaling through the use of semaphore
        – Use only semaphore increment operation (This is always non-
          blocking)
     • Sending data through pipes or other FD
        – Make sure that the pipe or FD that is used is set in non-
          blocking mode
                     Signals
• Communication with rest of the code
  – Using semaphore to signal




  – Using Global Variables
                  Signals
• Communication with the rest of the code
                       Signals
• Nonlocal Control Transfers in Signal Handlers
  – Can do nonlocal transfer of control out of the
    signal handler
     • Use setjmp/longjmp or sigsetjmp/siglongjmp calls
  – This does not clear up the stack properly, so care
    should be taken to use this
  – Could also leave data structures in in-consistent
    state, option to avoid this could be
     • Block signals while manipulating such data structure so
       that the longjmp will always happen only when
       structures are consistent
     • Force the structures to be consistent within the signal
       handler
                   Signals
• Nonlocal Control Transfers in signal handlers
            Threads and Signals
• Threads and Signal Interactions
  – Signal handlers are common for all threads
  – Signal disposition (block/not-blocked) is per
    thread
  – Synchronous signals are delivered to the thread
    that caused the event
     • For e.g. SEGV, FPE etc.
  – Signals generated by asynchronous events and
    from outside the process can be delivered to any
    thread which has not blocked the signal
           Threads and Signals
• Recommendation for signals in multithread
  programs
  – Avoid using signals in multi-thread programs
  – If you absolutely must, then:
     • Separate Signal Handling Thread
        – Have a separate signal handling thread for handling signals
          that are generated to the process
        – In this thread use sigwait mechanism to handle this signal
        – In all the other threads, this signal(s) must be blocked
     • Handling Synchronous or thread directed signals
        – Here the handler runs in the context of the correct thread
        – Have the handler installed and the threads of interest must
          unblock these signals.
            Threads and Signals
• Problem Statement
  – TCP echo server program, where each client
    connection is handled in a thread
  – Configuration file specifies the
     • Server port to listen on
     • Limit to the number of clients we will accept
       simultaneously
  – When program is running, user can change the
    configuration file, and send SIGHUP to the process
    to update the configuration during run time
  – If in the number of clients currently serviced
    exceeds the new config, they should be closed to
    bring it within this limit
                      Threads and Signals

                    Initialize (read config file, start server etc.)

            Open a pipe for communication with SIGHUP handling thread

                      Start SIGHUP handling thread

 SIGHUP thread,         wait on select (Server socket + pipe)
Wait on sigwait
for SIGHUP and
                      If message on pipe, handle the new config
then read the new
                      If message on socket accept the connection
configuration and
                      and start a thread to handle this connection
send message on
the pipe to main
thread.
                                                          Handle the client connection, in
                                                          case of error shut down, or in case
                                                          of receiving SIGUSR1 signal also
                                                          shutdown
Threads and Signals
                     Signals
• Standard Signals
                           Signals
• System call for signals related functions
  – Generating a signal
     • kill, sigqueue, raise
         – Kill and sigqueue take a pid which specifies the process to
           send the signal to
              » Signals can be sent to single process, a process group, all
                 process to which this process has permission
         – If signal to be sent is zero, then no signal is sent, but error
           checking is performed
              » Can be used to check if the process with pid exists
         – Raise is the same as kill with pid being the same process
         – Sigqueue can specify the parameter that should be passed to
           the signal handler
              » This will be queued and multiple such signals will not be
                 lost and delivered when the process unblocks the signal if
                 signal is real time signal
                            Signals
• System calls for signal related functions
  – Generating signals
     • kill, sigqueue, raise
         – If the signal to be sent to the calling process itself, then the
           signal will be delivered before the completion of the call
     • pthread_kill
         – Can be used to send a signal to the specified thread
         – Can be used to send signals to threads within the same
           process
  – Installing the signal handler
     • sigaction, signal
                           Signals
• System call for signal related functions
  – Installing the signal handler
     • sigaction, signal
        – Signal was the original function to install the signal handler
        – Does not support handler which takes arguments, and also
          the handler is replaced with the original handler after the first
          invocation
        – Does not mask the signal that is being handled, till the handler
          completes
        – sigaction solves all the above problems, and is more robust
          and should be used to install the signal handlers
  – Specify an alternate stack
     • sigaltstack
                          Signals
• System call for signal related functions
  – Blocking/Unblocking of signals
     • sigprocmask, pthread_sigmask
        – Can be used to add signals to the set of blocked signals
        – Remove signals from the set of blocked signals
        – Replace the current set with a new set of blocked signals
        – sigprocmask should be used in single threaded process, and
          changes the mask for the entire process
             » Usage is undefined in a multi-threaded process
        – pthread_sigmask changes the signal mask for the calling
          thread in a process
     • sigemptyset, sigaddset, sigdelset, sigismember, sigfillset
        – Helper functions that can be used to manipulate the signals in
          a signal mask
        – The signal mask is a parameter to the sigprocmask and
          pthread_sigmask functions
                           signals
• System call for signal related functions
  – Synchronously waiting for signals
     • sigwaitinfo, sigwait, sigtimedwait
        – These functions allow to specify a set of signals and then
          block for one of the signals in that set to be delivered to the
          application
        – In case the signal is already delivered, the function
          immediately returns, else it blocks till the signal is delivered
        – The timed version allows to specify a timeout value for the
          wait
        – The sigwaitinfo version also gets the additional parameter of
          info, which specifies the signal parameter and other signal
          related information
Data Structure Repair
          Data Structure Repair
• Goal of the system
  – During operation of the program, the state (data
    structures) of the program may get corrupted
     • This is due to bugs in the program
  – Due to these corruptions the program may crash
  – This necessitates a reload of the system
     • If the state is persistent then even a reload will not help
       and the state should be reset to initial or some known
       state
           Data Structure Repair
• Goal
  – When the state corruption is detected
     • Invoke a repair function that can correct the corrupted
       data structures
     • This will allow the program to continue to operate
         – May sometime mean loss of some information, if the repair
           cannot be done completely
         – But still allows the system to continue to offer services and
           wait for a scheduled maintenance rather than abrupt down
           time
           Data Structure Repair
• Repair
  – Detect a corruption and then correct it
  – Based on
     • Specification of the data structure consistency
       definitions
     • Use these specifications to detect and repair corruption
  – Generic Models
     • Generic language for defining the consistency
     • Allows to write a generic repair function that can be
       used to perform the job
         Data Structure Repair
• Detection of corruption and repair
  – Done on periodic basis
  – Done after every or a set of operations of the
    system
  – Done when the system crashes (or other mis-
    behavior)
          Data Structure Repair
• Issues in wide spread usage
  – Cost of defining a generic language and
    mechanisms and integrating that with the
    applications
     • Else cost of defining and writing custom repair
       algorithms for the individual applications
  – The percentage of errors that can be caught and
    fixed
     • Corruptions may not get detected easily and could lead
       to further corruptions
        Data Structure Repair
• Sample Programs
                             References
•   http://www.cocoadev.com/index.pl?SignalSafety
•   http://www.gnu.org/s/libc/manual/html_node/Signal-Handling.html#Signal-
    Handling
•   http://www.gnu.org/s/libc/manual/html_node/Longjmp-in-Handler.html
•   http://markmail.org/message/ashxvg2nvdi6hiqe#query:using%20longjmp%20in%
    20signal%20handlers+page:1+mid:ashxvg2nvdi6hiqe+state:results
•   http://publib.boulder.ibm.com/infocenter/systems/index.jsp?topic=/com.ibm.aix.g
    enprogc/doc/genprogc/signal_mgmt.htm
•   http://people.csail.mit.edu/rinard//paper/sms03.pdf
•   http://content.digitalwell.washington.edu/msr/external_release_talks_12_05_200
    5/12102/lecture.htm
•   http://users.ece.utexas.edu/~elkarabl/files/p64-elkarablieh.pdf
•   http://dspace.mit.edu/bitstream/handle/1721.1/30474/MIT-CSAIL-TR-2004-
    035.pdf?sequence=2
 Thanks for your
Time and Patience

				
DOCUMENT INFO
Shared By:
Stats:
views:440
posted:3/31/2010
language:English
pages:39