【Linux】信号(Signal)

Posted by 西维蜀黍 on 2021-02-16, Last Modified on 2021-09-21

信号(Signal)

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 to notify it of an event. Signals originated in 1970s Bell Labs Unix and were later specified in the POSIX standard.

When a signal is sent, the operating system interrupts the target process’ normal flow of execution to deliver the signal. Execution can be interrupted during any non-atomic instruction. If the process has previously registered a signal handler, that routine is executed. Otherwise, the default signal handler is executed.

Typing certain key combinations at the controlling terminal of a running process causes the system to send it certain signals:

  • Ctrl + C (in older Unixes, DEL) sends an INT signal (“interrupt”, SIGINT); by default, this causes the process to terminate.
  • Ctrl + Z sends a TSTP signal (“terminal stop”, SIGTSTP); by default, this causes the process to suspend execution.
  • Ctrl + \ sends a QUIT signal (SIGQUIT); by default, this causes the process to terminate and dump core.
  • Ctrl + T (not supported on all UNIXes) sends an INFO signal (SIGINFO); by default, and if supported by the command, this causes the operating system to show information about the running command.

Handling Signals

Signal handlers can be installed with the signal() or sigaction() system call. If a signal handler is not installed for a particular signal, the default handler is used. Otherwise the signal is intercepted and the signal handler is invoked.

The process can also specify two default behaviors, without creating a handler: ignore the signal (SIG_IGN) and use the default signal handler (SIG_DFL).

The reason for handling these signals is usually so your program can tidy up as appropriate before actually terminating. For example, you might want to save state information, delete temporary files, or restore the previous terminal modes. Such a handler should end by specifying the default action for the signal that happened and then reraising it; this will cause the program to terminate with that signal, as if it had not had a handler.

There are two signals which cannot be intercepted and handled: SIGKILL and SIGSTOP.


A process can change the disposition of a signal using sigaction(2) or signal(2). (The latter is less portable when establishing a signal handler) Using these system calls, a process can elect one of the following behaviors to occur on delivery of the signal: perform the default action; ignore the signal; or catch the signal with a signal handler, a programmer-defined function that is automatically invoked when the signal is delivered. (By default, the signal handler is invoked on the normal process stack. It is possible to arrange that the signal handler uses an alternate stack; see sigaltstack(2) for a discussion of how to do this and when it might be useful.)

The signal disposition is a per-process attribute: in a multithreaded application, the disposition of a particular signal is the same for all threads.

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.

signal()

SYNOPSIS

#include <signal.h>

typedef void (*sighandler_t)(int);

sighandler_t signal(int signum, sighandler_t handler);

Demo

The cleanest way for a handler to terminate the process is to raise the same signal that ran the handler in the first place. Here is how to do this:

volatile sig_atomic_t fatal_error_in_progress = 0;

void
fatal_error_signal (int sig)
{
  /* Since this handler is established for more than one kind of signal, 
     it might still get invoked recursively by delivery of some other kind
     of signal.  Use a static variable to keep track of that. */
  if (fatal_error_in_progress)
    raise (sig);
  fatal_error_in_progress = 1;

  /* Now do the clean up actions:
     - reset terminal modes
     - kill child processes
     - remove lock files */
  

  /* Now reraise the signal.  We reactivate the signal’s
     default handling, which is to terminate the process.
     We could just call exit or abort,
     but reraising the signal sets the return status
     from the process correctly. */
  signal (sig, SIG_DFL);
  raise (sig);
}

POSIX signals

The list below documents the signals specified in the Single Unix Specification. All signals are defined as macro constants in the <signal.h> header file. The name of the macro constant consists of a “SIG” prefix followed by a mnemonic name for the signal.

First the signals described in the original POSIX.1-1990 standard.

Signal     Value     Action   Comment
──────────────────────────────────────────────────────────────────────
SIGHUP        1       Term    Hangup detected on controlling terminal
                              or death of controlling process
SIGINT        2       Term    Interrupt from keyboard
SIGQUIT       3       Core    Quit from keyboard
SIGILL        4       Core    Illegal Instruction
SIGABRT       6       Core    Abort signal from abort(3)
SIGFPE        8       Core    Floating-point exception
SIGKILL       9       Term    Kill signal
SIGSEGV      11       Core    Invalid memory reference
SIGPIPE      13       Term    Broken pipe: write to pipe with no
                              readers; see pipe(7)
SIGALRM      14       Term    Timer signal from alarm(2)
SIGTERM      15       Term    Termination signal
SIGUSR1   30,10,16    Term    User-defined signal 1
SIGUSR2   31,12,17    Term    User-defined signal 2
SIGCHLD   20,17,18    Ign     Child stopped or terminated
SIGCONT   19,18,25    Cont    Continue if stopped
SIGSTOP   17,19,23    Stop    Stop process
SIGTSTP   18,20,24    Stop    Stop typed at terminal
SIGTTIN   21,21,26    Stop    Terminal input for background process
SIGTTOU   22,22,27    Stop    Terminal output for background process
Next the signals not in the POSIX.1-1990 standard but described in SUSv2 and POSIX.1-2001.

Signal       Value     Action   Comment
────────────────────────────────────────────────────────────────────
SIGBUS      10,7,10     Core    Bus error (bad memory access)
SIGPOLL                 Term    Pollable event (Sys V).
                                Synonym for SIGIO
SIGPROF     27,27,29    Term    Profiling timer expired
SIGSYS      12,31,12    Core    Bad system call (SVr4);
                                see also seccomp(2)
SIGTRAP        5        Core    Trace/breakpoint trap

SIGURG      16,23,21    Ign     Urgent condition on socket (4.2BSD)
SIGVTALRM   26,26,28    Term    Virtual alarm clock (4.2BSD)
SIGXCPU     24,24,30    Core    CPU time limit exceeded (4.2BSD);
                                see setrlimit(2)
SIGXFSZ     25,25,31    Core    File size limit exceeded (4.2BSD);
                                see setrlimit(2)

Up  to  and  including Linux 2.2, the default behavior for SIGSYS, SIGXCPU, SIGXFSZ, and (on architectures other than SPARC and MIPS) SIGBUS was to terminate
the process (without a core dump).  (On some other UNIX systems the default action for SIGXCPU and SIGXFSZ is to terminate the process without a core  dump.)
Linux 2.4 conforms to the POSIX.1-2001 requirements for these signals, terminating the process with a core dump.

SIGINT - Control + C - 优雅杀掉指定进程

The SIGINT signal is sent to a process by its controlling terminal when a user wishes to interrupt the process. This is typically initiated by pressing Ctrl+C, but on some systems, the “delete” character or “break” key can be used.

SIGQUIT - Ctrl + \

The SIGQUIT signal is similar to SIGINT, except that it’s controlled by a different key—the QUIT character.

By default, this causes the process to terminate and dump core.

You can think of this as a program error condition “detected” by the user.

SIGTERM - 优雅杀掉指定进程

The SIGTERM signal is sent to a process to request its termination. Unlike the SIGKILL signal, it can be caught and interpreted or ignored by the process. This allows the process to perform nice termination releasing resources and saving state if appropriate.

The shell command kill generates SIGTERM by default.

SIGINT is nearly identical to SIGTERM.

当使用 kill 杀掉进程时,可以通过 strace 看到进程收到的 signal:

# 发送 SIGTERM 以结束这个进程, by `kill 114469`
$ strace -ttp 114469
...
12:12:15.227492 futex(0x2e1c348, FUTEX_WAIT_PRIVATE, 0, NULL) = ? ERESTARTSYS (To be restarted if SA_RESTART is set)
12:12:55.291152 --- SIGTERM {si_signo=SIGTERM, si_code=SI_USER, si_pid=114561, si_uid=0} ---
12:12:55.291230 rt_sigprocmask(SIG_UNBLOCK, [TERM], NULL, 8) = 0
12:12:55.291319 getpid()                = 114469
12:12:55.291363 gettid()                = 114469
12:12:55.291402 tgkill(114469, 114469, SIGTERM) = 0
12:12:55.291760 --- SIGTERM {si_signo=SIGTERM, si_code=SI_TKILL, si_pid=114469, si_uid=0} ---
12:12:55.291804 rt_sigaction(SIGTERM, {SIG_DFL, ~[], SA_RESTORER|SA_STACK|SA_RESTART|SA_SIGINFO, 0x7f7b485d8390}, NULL, 8) = 0
12:12:55.292002 rt_sigprocmask(SIG_UNBLOCK, [TERM], NULL, 8) = 0
12:12:55.292118 getpid()                = 114469
12:12:55.292193 gettid()                = 114469
12:12:55.292260 tgkill(114469, 114469, SIGTERM) = 0
12:12:55.292332 --- SIGTERM {si_signo=SIGTERM, si_code=SI_TKILL, si_pid=114469, si_uid=0} ---
12:12:55.295492 +++ killed by SIGTERM +++

# 发送 SIGKILL 以结束这个进程, by `kill -9 115677`
$ strace -ttp 115677
strace: Process 115677 attached
12:25:00.762968 futex(0x2e47540, FUTEX_WAIT_PRIVATE, 0, NULL <unfinished ...>
12:25:13.831309 +++ killed by SIGKILL +++

SIGKILL - 强制杀掉指定进程

The SIGKILL signal is sent to a process to cause it to terminate immediately (kill).

In contrast to SIGTERM and SIGINT, this signal cannot be caught or ignored, and the receiving process cannot perform any clean-up upon receiving this signal.

This signal is usually generated only by explicit request. Since it cannot be handled, you should generate it only as a last resort, after first trying a less drastic method such as C-c or SIGTERM. If a process does not respond to any other termination signals, sending it a SIGKILL signal will almost always cause it to go away.

In fact, if SIGKILL fails to terminate a process, that by itself constitutes an operating system bug which you should report.\

SIGSTOP - 强制杀掉指定进程

stop (cannot be caught or ignored)

SIGINFO - Control + T

SIGINFO (not supported on all UNIXes) sends an INFO signal (SIGINFO).

By default, and if supported by the command, this causes the operating system to show information about the running command.

SIGTSTP - Control + Z - 挂起进程

  • Ctrl-Z sends a TSTP signal (“terminal stop”, SIGTSTP)
  • stop signal generated from keyboard

SIGILL

The SIGILL signal is sent to a process when it attempts to execute an illegal, malformed, unknown, or privileged instruction.

SIGABRT and SIGIOT

The SIGABRT and SIGIOT signal is sent to a process to tell it to abort, i.e. to terminate. The signal is usually initiated by the process itself when it calls abort() function of the C Standard Library, but it can be sent to the process from outside like any other signal.

SIGHUP

The SIGHUP (“hang-up”) signal is used to report that the user’s terminal is disconnected, perhaps because a network or telephone connection was broken.

SIGQUIT - Ctrl + \

  • default action: create core image
  • quit program

SIGSEGV

Segmentation Fault

In computing, a segmentation fault (often shortened to segfault) or access violation is a fault, or failure condition, raised by hardware with memory protection, notifying an operating system (OS) the software has attempted to access a restricted area of memory (a memory access violation). On standard x86 computers, this is a form of general protection fault. The OS kernel will, in response, usually perform some corrective action, generally passing the fault on to the offending process by sending the process a signal. Processes can in some cases install a custom signal handler, allowing them to recover on their own,[1] but otherwise the OS default signal handler is used, generally causing abnormal termination of the process (a program crash), and sometimes a core dump.

Demo

A segmentation fault (segfault) basically means you did something bad with pointers. This is probably a segfault:

char *c = NULL;
...
*c; // dereferencing a NULL pointer

Or this:

char *c = "Hello";
...
c[10] = 'z'; // out of bounds, or in this case, writing into read-only memory

Or maybe this:

char *c = new char[10];
...
delete [] c;
...
c[2] = 'z'; // accessing freed memory

Same basic principle in each case - you’re doing something with memory that isn’t yours.

Reference