Sigaction

Last updated

In computing, sigaction is a function API defined by POSIX to give the programmer access to what should be a program's behavior when receiving specific OS signals.

Contents

General

In Unix-like operating systems, one means of inter-process communication is through signals. When an executing unit (process or thread) receives a signal from the OS, it should react in some way defined by the datasheet and the conventional meaning of this signal (i.e. by dumping its data, stopping execution, synchronizing something...).

The sigaction() system call is used to declare the behavior of the program should it receive one particular non-system-reserved signal. This is done by giving along with the system call a structure containing, among others, a function pointer to the signal handling routine. Some predefined signals (such as SIGKILL) have locked behavior that is handled by the system and cannot be overridden by such system calls.

sigaction structure

The POSIX standard requires that the sigaction structure be defined as below in the <signal.h> header file and it should contain at least the following fields:

structsigaction{void(*sa_handler)(int);/* address of signal handler */sigset_tsa_mask;/* additional signals to block */intsa_flags;/* signal options *//* alternate signal handler */void(*sa_sigaction)(int,siginfo_t*,void*);};

Implementations are free to define additional, possibly non-portable fields. The sa_handler member specifies the address of a function to be called when the process receives the signal. The signal number is passed as an integer argument to this function. The sa_mask member specifies additional signals to be blocked during the execution of signal handler. sa_mask must be initialized with sigemptyset(3). The sa_flags member specifies some additional flags. sa_sigaction is an alternate signal handler with different set of parameters. Only one signal handler must be specified, either sa_handler or sa_sigaction. If it is desired to use sa_sigaction instead of sa_handler, SA_SIGINFO flag must be set.

Replacement of deprecated signal()

The sigaction() function provides an interface for reliable signals in replacement of the unreliable and deprecated signal() function. Signal handlers installed by the signal() interface will be uninstalled immediately prior to execution of the handler. Permanent handlers must therefore be reinstalled by a call to signal() during the handler's execution, causing unreliability in the event a signal of the same type is received during the handler's execution but before the reinstall. Handlers installed by the sigaction() interface can be installed permanently and a custom set of signals can be blocked during the execution of the handler. These signals will be unblocked immediately following the normal termination of the handler (but not in the event of an abnormal termination such as a C++ exception throw.)

Use in C++

In C++, the try {/* ... */} catch {/* ... */} programming structure may be (depending on host platforms) based on signalling. To catch signals translated into C++ exceptions, special compiler switches may be necessary on some platforms such as -fnon-call-exceptions for GCC and the Intel C Compiler. [1]

Example

#include<stdio.h>#include<stdlib.h>#include<string.h>#include<unistd.h>#include<sys/wait.h>#include<signal.h>#define NUMCHLDS 10voidsigchld_handler(int,siginfo_t*,void*);sig_atomic_tnexitedchlds=0;intmain(intargc,char*argv[]){structsigactionact;memset(&act,0,sizeof(structsigaction));sigemptyset(&act.sa_mask);act.sa_sigaction=sigchld_handler;act.sa_flags=SA_SIGINFO;if(-1==sigaction(SIGCHLD,&act,NULL)){perror("sigaction()");exit(EXIT_FAILURE);}for(inti=0;i<NUMCHLDS;i++){switch(fork()){case0:/*                                 * Older OS implementations that do not correctly implement                                 * the siginfo structure will truncate the exit code                                 * by masking it with 0xFF.                                 */return1234567890;/* NOTREACHED */case-1:write(STDERR_FILENO,"fork ERROR!",11);exit(EXIT_FAILURE);/* NOTREACHED */default:printf("Child created\n");}}while(1){if(nexitedchlds<NUMCHLDS)pause();elseexit(EXIT_SUCCESS);}/* NOTREACHED */return0;}voidsigchld_handler(intsigno,siginfo_t*sinfo,void*context){pid_tproc;while((proc=waitpid(-1,NULL,WNOHANG))>0){/* signal main thread */nexitedchlds++;/*                 * note: printf() is not signal-safe!   * don't use it in a signal handler.                 * si_code is the full 32 bit exit code from the child (see also waitid()).   */printf("sinfo->si_pid = %ld\nproc = %ld\nexit code %d exit reason %d\n",(long)sinfo->si_pid,(long)proc,sinfo->si_status,sinfo->si_code);}}

Related Research Articles

C (programming language) general-purpose programming language

C is a general-purpose, procedural computer programming language supporting structured programming, lexical variable scope, and recursion, with a static type system. By design, C provides constructs that map efficiently to typical machine instructions. It has found lasting use in applications previously coded in assembly language. Such applications include operating systems and various application software for computer architectures that range from supercomputers to PLCs and embedded systems.

On Unix and Unix-like computer operating systems, a zombie process or defunct process is a process that has completed execution but still has an entry in the process table: it is a process in the "Terminated state". This occurs for the child processes, where the entry is still needed to allow the parent process to read its child's exit status: once the exit status is read via the wait system call, the zombie's entry is removed from the process table and it is said to be "reaped". A child process always first becomes a zombie before being removed from the resource table. In most cases, under normal system operation zombies are immediately waited on by their parent and then reaped by the system – processes that stay zombies for a long time are generally an error and cause a resource leak, but the only resource they occupy is the process table entry – process ID.

Berkeley sockets is an application programming interface (API) for Internet sockets and Unix domain sockets, used for inter-process communication (IPC). It is commonly implemented as a library of linkable modules. It originated with the 4.2BSD Unix operating system, released in 1983.

In computing, a computer program or subroutine is called reentrant if multiple invocations can safely run concurrently. The concept applies even on a single processor system, where a reentrant procedure can be interrupted in the middle of its execution and then safely be called again ("re-entered") before its previous invocations complete execution. The interruption could be caused by an internal action such as a jump or call, or by an external action such as an interrupt or signal. The previous invocations may resume correct execution before the reentered invocation completes, unlike recursion, where the previous invocations may only resume correct execution once the reentered invocation completes.

In object-oriented programming, in languages such as C++, and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated. This concept is an important part of the (runtime) polymorphism portion of object-oriented programming (OOP). In short, a virtual function defines a target function to be executed, but the target might not be known at compile time.

In computing, a parent process is a process that has created one or more child processes.

The syntax of the C programming language is the set of rules governing writing of software in the language. It is designed to allow for programs that are extremely terse, have a close relationship with the resulting object code, and yet provide relatively high-level data abstraction. C was the first widely successful high-level language for portable operating-system development.

In computer programming, a callback, also known as a "call-after" function, is any executable code that is passed as an argument to other code; that other code is expected to call back (execute) the argument at a given time. This execution may be immediate as in a synchronous callback, or it might happen at a later time as in an asynchronous callback. Programming languages support callbacks in different ways, often implementing them with subroutines, lambda expressions, blocks, or function pointers.

stat is a Unix system call that returns file attributes about an inode. The semantics of stat vary between operating systems. As an example, Unix command ls uses this system call to retrieve information on files that includes:

Signals are a limited form of inter-process communication (IPC), typically used in Unix, Unix-like, and other POSIX-compliant operating systems. A signal is an asynchronous notification sent to a process or to a specific thread within the same process in order to notify it of an event that occurred. Signals originated in 1970s Bell Labs Unix and have been more recently specified in the POSIX standard.

The functions getaddrinfo and getnameinfo convert domain names, hostnames, and IP addresses between human-readable text representations and structured binary formats for the operating system's networking API. Both functions are contained in the POSIX standard application programming interface (API).

In computer programming, the term hooking covers a range of techniques used to alter or augment the behaviour of an operating system, of applications, or of other software components by intercepting function calls or messages or events passed between software components. Code that handles such intercepted function calls, events or messages is called a hook.

Exception handling syntax is the set of keywords and/or structures provided by a computer programming language to allow exception handling, which separates the handling of errors that arise during a program's operation from its ordinary processes. Syntax for exception handling varies between programming languages, partly to cover semantic differences but largely to fit into each language's overall syntactic structure. Some languages do not call the relevant concept "exception handling"; others may not have direct facilities for it, but can still provide means to implement it.

setcontext is one of a family of C library functions used for context control. The setcontext family allows the implementation in C of advanced control flow patterns such as iterators, fibers, and coroutines. They may be viewed as an advanced version of setjmp/longjmp; whereas the latter allows only a single non-local jump up the stack, setcontext allows the creation of multiple cooperative threads of control, each with its own stack.

setjmp.h is a header defined in the C standard library to provide "non-local jumps": control flow that deviates from the usual subroutine call and return sequence. The complementary functions setjmp and longjmp provide this functionality.

In the C Standard Library, signal processing defines how a program handles various signals while it executes. A signal can report some exceptional behavior within the program, or a signal can report some asynchronous event outside the program.

select is a system call and application programming interface (API) in Unix-like and POSIX-compliant operating systems for examining the status of file descriptors of open input/output channels. The select system call is similar to the poll facility introduced in UNIX System V and later operating systems. However, with the c10k problem, both select and poll have been superseded by the likes of kqueue, epoll, /dev/poll and I/O completion ports.

This article describes the syntax of the C# programming language. The features described are compatible with .NET Framework and Mono.

getopt is a C library function used to parse command-line options of the Unix/POSIX style. It is a part of the POSIX specification, and is universal to Unix-like systems.

In computers, XC is a programming language for real-time embedded parallel processors, targeted at the XMOS XCore processor architecture.

References