Linux signal signal usage explanation and precautions

Source: Internet
Author: User
Tags arithmetic signal handler terminates

A signal is a software interrupt, an asynchronous communication method that handles an asynchronous event. For example, we run the program in the terminal, by pressing the keyboard "CTRL + C", you can send a SIGINT interrupt signal to stop the program to run.
There are 3 ways to handle the signal:
1. Ignoring this signal, most signals can be handled as such. Except for Sigkill and sigstop, they must not be ignored.
2. Capture the signal, the user customizes a signal processing function, when the signal occurs, it will trigger the call to the custom signal function. Signals Sigkill and sigstop cannot be captured.
3. System default action, the default action for most signals is to terminate the process. Some signals "terminate +core", dump the memory image of the process and save it in the file.

Using the function signal to set the signal processing function, the code is as follows:

    1. #include <stdio.h>
    2. #include <stdlib.h>
    3. #include <sys/types.h>
    4. #include <sys/wait.h>
    5. #include <signal.h>
    6. static void signal_usr (int);
    7. int main (void)
    8. {
    9. if (sig_err==signal (SIGUSR1,SIGNAL_USR))
    10. printf ("Cant catch SIGUSR1");
    11. if (sig_err==signal (SIGUSR2,SIGNAL_USR))
    12. printf ("Cant catch SIGUSR2");
    13. for (;;)
    14. Pause ();
    15. }
    16. static void signal_usr (int signo)
    17. {
    18. if (Sigusr1==signo)
    19. printf ("Received sigusr1\n");
    20. else if (Sigusr2==signo)
    21. printf ("Received sigusr2\n");
    22. Else
    23. printf ("Received signal%d\n", signo);
    24. }
Copy Code

Run:
$./a.out & Background Run
[1] 9016 process number
$ KILL-USR2 9016 sends a SIGUSR2 signal to the process via kill (1)
$ received SIGUSR2 display captures the signal

$ KILL-USR1 9016 sends a SIGUSR1 signal to the process via kill (1)
$ received SIGUSR1 display captures the signal

$ kill-9 9016 sends a sigkill signal to the process via kill (1) or 9.
$
[1]+ killed./a.out the process was terminated
$

The following content is collected from the networkwe run the following command to see a list of supported signals from Linux: ~$ kill-l
1) SIGHUP 2) SIGINT 3) Sigquit 4) Sigill
5) SIGTRAP 6) SIGABRT 7) Sigbus 8) SIGFPE
9) SIGKILL) SIGUSR1 one) SIGSEGV) SIGUSR2
) SI Gpipe) (SIGALRM) SIGTERM) SIGCHLD
() sigcont) SIGSTOP) SIGTSTP) Sigttin
() Sigttou) Sigurg 24) SIGXCPU) Sigxfsz
() sigvtalrm) sigprof sigwinch) SIGIO
() SIGPWR) sigsys) sigrtmin N+1
Sigrtmin+2) sigrtmin+3 (sigrtmin+4) sigrtmin+5
(+) sigrtmin+6) sigrtmin+7) SIG Rtmin+9
sigrtmin+10) sigrtmin+11 (sigrtmin+12) sigrtmin+13
) sigrtmin+14) sigrtmin+15 -14) SIGRTMAX-13
SIGRTMAX-12) (SIGRTMAX-11) SIGRTMAX-10) SIGRTMAX-9
() SIGRTMAX-8) SIGRTMAX-7 58) SIGRTMAX-6 (SIGRTMAX-5
) SIGRTMAX-4) SIGRTMAX-3 () SIGRTMAX-2) SIGRTMAX-1
Sigrtmax in the list, the signals numbered 1 ~ 31 are signals that are supported by traditional UNIX, are unreliable signals (not real-time), and the signals numbered 32 to 63 are later expanded, called reliable signals (real-time signals). The difference between unreliable and reliable signals is that the former does not support queueing and may cause signal loss, while the latter does not. below we discuss a signal with a number less than sigrtmin. 1) SIGHUP
This signal is issued at the end of the user terminal connection (normal or abnormal), usually at the end of the control process of the terminal to notify the same session of the various jobs, when they are no longer associated with the control terminal. when you log in to Linux, the system is assigned to a terminal (Session) of the logged-on user. All programs running at this terminal, including the foreground process group and the background process group, usually belong to this Session. When the user exits the Linux login, the foreground process group and the background will receive a sighup signal to the terminal output process. The default action for this signal is to terminate the process, so the foreground process group and the process that has terminal output in the background will be aborted. However, this signal can be captured, such as wget can capture the sighup signal, and ignore it, so even if you quit the Linux login, wget can continue to download. In addition, for daemons with terminal disengagement, this signal is used to notify it to reread the configuration file. 2) SIGINT
A program termination (interrupt) signal, issued when the user types the intr character (usually ctrl-c), to inform the foreground process group that the process is terminated. 3) sigquit
Similar to SIGINT, but controlled by the quit character (usually ctrl-\). The process generates a core file when it receives a sigquit exit, similar to a program error signal in this sense. 4) Sigill
An illegal instruction was executed. This is usually due to an error in the executable file itself or an attempt to execute a data segment. This signal can also be generated when a stack overflows. 5) SIGTRAP
Generated by a breakpoint instruction or other trap instruction. Used by debugger. 6) SIGABRT
Invokes the signal generated by the abort function. 7) Sigbus
Illegal address, including memory address alignment (alignment) error. For example, a four-word integer is accessed, but its address is not a multiple of 4. It differs from SIGSEGV in that the latter is triggered by illegal access to a legitimate storage address (such as Access does not belong to its own storage space or read-only storage space). 8) SIGFPE
Emitted when a fatal arithmetic operation error occurs. This includes not only floating-point arithmetic errors, but also all other arithmetic errors such as overflow and divisor 0. 9) SIGKILL
Used to immediately end the run of the program. This signal cannot be blocked, processed, or ignored. If an administrator discovers that a process is not terminating, try sending this signal. ) SIGUSR1
Leave it to the userOne ) SIGSEGV
An attempt was made to access memory that is not assigned to itself or to write data to a memory address that does not have write permissions. SIGUSR2)
Leave it to the user Sigpipe)
Pipe rupture. This signal is usually generated between interprocess communication, such as two processes with FIFO (pipeline) communication, the read pipeline is not opened or terminated unexpectedly to the pipeline to write, the writing process will receive sigpipe signal. In addition, two processes with the socket communication, the write process when the socket is written, the read process has been terminated. SIGALRM)
A clock timing signal that calculates the actual time or clock time. The alarm function uses this signal. SIGTERM)
The end of program (terminate) signal, unlike Sigkill, is that the signal can be blocked and processed. Typically used to require the program to exit gracefully, the shell command kill generates this signal by default. If the process does not stop, we will try to Sigkill. SIGCHLD)
The parent process receives this signal at the end of the child process. If the parent process does not process the signal and does not wait for the (wait) child process, although the child process terminates, it also occupies the table entry in the kernel process table, when the child process is called a zombie process. In this case we should avoid (the parent process either ignores the sigchild signal, or catches it, or wait for its derived child process, or the parent process terminates first, and the termination of the child process is automatically taken over by the Init process). ) Sigcont
Let a stop (stopped) process continue execution. This signal cannot be blocked. You can use a handler to get the program to do certain work when the stopped state changes to continue. For example, to re-display the prompt SIGSTOP)
Stop (stopped) the execution of the process. Notice the difference between it and terminate and interrupt: The process is not over yet, just pause execution. This signal cannot be blocked, processed or ignored. SIGTSTP)
Stops the process from running, but the signal can be processed and ignored. This signal is emitted when the user types Susp characters (usually ctrl-z) ) Sigttin
When a background job wants to read data from the user terminal, all processes in the job receive a sigttin signal. By default, these processes stop executing. Sigttou)
Similar to Sigttin, but received when writing a terminal (or modifying terminal mode). Sigurg)
When there is "emergency" data or Out-of-band data arrives at the socket. ) sigxcpu
CPU time resource limit exceeded. This restriction can be read/changed by Getrlimit/setrlimit. Sigxfsz)
When the process attempts to enlarge the file so that it exceeds the file size resource limit. SIGVTALRM)
Virtual clock signal. is similar to SIGALRM, but calculates the CPU time that is consumed by the process. SIGPROF)
Similar to SIGALRM/SIGVTALRM, but includes the CPU time used by the process and the time of the system call. Sigwinch)
emitted when the window size changes. ) SIGIO
The file descriptor is ready to start the input/output operation. SIGPWR)
Power Failure Sigsys)
An illegal system call. In the signals listed above, the program can not capture, block or ignore the signal is: sigkill,sigstop
Signals that cannot be restored to the default action are: Sigill,sigtrap
The default causes the process to abort the signal is: Sigabrt,sigbus,sigfpe,sigill,sigiot,sigquit,sigsegv,sigtrap,sigxcpu,sigxfsz
The signal that causes the process to exit by default is: SIGALRM,SIGHUP,SIGINT,SIGKILL,SIGPIPE,SIGPOLL,SIGPROF,SIGSYS,SIGTERM,SIGUSR1,SIGUSR2,SIGVTALRM
The signal that causes the process to stop by default is: Sigstop,sigtstp,sigttin,sigttou
The default process ignores signals such as: Sigchld,sigpwr,sigurg,sigwinch In addition, Sigio in SVR4 is exited, is ignored in 4.3BSD, Sigcont is continued when the process hangs, otherwise it is ignored and cannot be blocked.

The following is a supplement to other netizens:

SIGHUP terminating process terminal line hang-off
SIGINT terminating process Interrupt process
Sigquit establish core file termination process, and generate core file
Sigill Creating a core file illegal directive
SIGTRAP build core file tracking self-trapping
Sigbus establishing a core file bus error
SIGSEGV creating core file Segment Illegal error
SIGFPE creating a core file floating point exception
Sigiot creating a core file to perform I/O self-trapping
SIGKILL Terminate process Kill process
Sigpipe terminating a process writing data to a pipeline that does not have a read process
Sigalarm Terminating process timer to
SIGTERM terminating process software termination signal
SIGSTOP stop signal stop process non-terminal
SIGTSTP stop signal to stop the process terminal
Sigcont ignore signal continue execution of a stopped process
Sigurg ignoring signal I/O emergency signal
SIGIO ignoring the signal descriptor can be I/O
SIGCHLD Ignore signal Notify parent process when child process stops or exits
Sigttou Stop process background process write terminal
Sigttin Stop process background process read Terminal
SIGXGPU terminating process CPU time-out
SIGXFSZ termination process file length too long
Sigwinch ignoring signal window size changes
SIGPROF terminating process statistics distribution graph with timer to time
SIGUSR1 terminating a process user-defined signal 1
SIGUSR2 terminating a process user-defined signal 2
SIGVTALRM terminating process virtual timer to time1) SIGHUP this signal at the end of the user terminal connection (normal or abnormal) issued, usually in the terminal control
At the end of the process, notify each job in the same session, and the control terminal
is no longer associated.
2) SIGINT program termination (interrupt) signal, which is emitted when the user types Intr characters (usually ctrl-c)
3) Sigquit and SIGINT are similar, but are controlled by the Quit character (usually ctrl). Process in response to receipt
Sigquit exit will produce a core file, in this sense similar to a program error letter
No..
4) Sigill executed an illegal instruction. This is usually due to an error in the executable file itself or an attempt to execute
Data segment. This signal can also be generated when a stack overflows.
5) The SIGTRAP is generated by a breakpoint instruction or other trap instruction. Used by debugger.
6) The SIGABRT program itself discovers the error and calls abort when it is generated.
6) Sigiot is generated on PDP-11 by IoT instructions, on other machines and SIGABRT.
7) Sigbus illegal address, including memory address alignment (alignment) error. Eg: access to a four word length
Integer, but its address is not a multiple of 4.
8) The SIGFPE is emitted when a fatal arithmetic operation error occurs. Includes not only floating-point arithmetic errors, but also overflow
The sum of the divisor is 0 and all other arithmetic errors.
9) SIGKILL is used to immediately end the operation of the program. This signal cannot be blocked, processed and ignored.
SIGUSR1 leave it to the user
One) SIGSEGV attempts to access memory that is not allocated to itself, or attempts to write data to a memory address that does not have write permissions.
SIGUSR2 left for users to use
Sigpipe Broken Pipe
SIGALRM clock timing signal, which calculates the actual time or clock time. The alarm function uses the
Signal.
SIGTERM program End (terminate) signal, unlike Sigkill, the signal can be blocked and
Processing. Usually used to ask the program to exit normally. The shell command kill default produces this
A signal.
SIGCHLD the parent process will receive this signal at the end of the child process.
Sigcont let a stop (stopped) process continue execution. This signal cannot be blocked. can be used
A handler that allows the program to complete a specific application when the stopped state changes to continue execution.
Job. For example, to re-display the prompt
SIGSTOP the execution of the Stop (stopped) process. Notice the difference between it and terminate and interrupt:
The process is not over yet, just pausing execution. This signal cannot be blocked, processed or ignored.
SIGTSTP stops the process from running, but the signal can be processed and ignored. When a user types Susp characters
(usually ctrl-z) sends this signal
Sigttin when a background job reads data from a user terminal, all processes in that job receive Sigttin
Signal. By default, these processes stop executing.
Sigttou is similar to Sigttin, but is received when writing a terminal (or modifying terminal mode).
Sigurg) is generated when "emergency" data or Out-of-band data arrives at the socket.
SIGXCPU exceeds the CPU time resource limit. This limit can be read by Getrlimit/setrlimit/
Change
Sigxfsz exceeds the file size resource limit.
() SIGVTALRM virtual clock signal. is similar to SIGALRM, but calculates the CPU time that is consumed by the process.
Sigprof is similar to SIGALRM/SIGVTALRM, but includes the CPU time used by the process and the system call
Time.
sigwinch) When the window size changes.
) The SIGIO file descriptor is ready to start the input/output operation.
SIGPWR Power FailureThere are two signals to stop a process: Sigterm and Sigkill. Sigterm is friendly and the process captures the signal and shuts down the program according to your needs. Before you close the program, you can end the open record file and complete the task you are doing. In some cases, if the process is working and cannot be interrupted, the process can ignore the sigterm signal. for Sigkill signals, the process cannot be ignored. This is a "I don't care what you are doing, stop immediately" signal. If you send a sigkill signal to the process, Linux stops the process there.

Signal commonly used four functions, kill (), raise (), alarm (), pause ().
Kill () and raise () are introduced first.
The Kill () function, which is Kill (2), passes the signal to the process or process group. The Raise () function allows a process to send a signal to itself.

function header files and prototypes
#include <signal.h>
int Kill (pid_t pid, int signo);
int raise (int signo);
Return value: If successful, returns 0, or 1 if an error occurs.

About the Kill function access value PID:
Positive: The process number to send the signal
0: The signal is sent to all processes in the same process group as the current process
-1: Signal is sent to all processes in the process table
<-1: Signal is sent to process group for each process of-pid

Raise (Signo) equivalent to Kill (Getpid (), Signo)

code example: A child process raise itself a sigstop signal, pausing itself, and the parent process killing the child process.

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <sys/wait.h>
  5. #include <signal.h>
  6. int main () {
  7. pid_t pid;
  8. int ret;
  9. if ((Pid=fork ()) <0) {
  10. printf ("Fork error!\n");
  11. Exit (1);
  12. } else if (pid==0) {
  13. printf ("Child%d was waiting for signal...\n", Getpid ());
  14. The child process sends itself a SIGSTOP signal to suspend the process
  15. Raise (SIGSTOP);
  16. The following code will not run because it was killed by the parent process during the pause process.
  17. printf ("I am killed, bye!\n");
  18. Exit (0);
  19. } else {
  20. Sleep (3);
  21. Wait child process without blocking, returns 0 if the child process does not exit
  22. if ((Waitpid (Pid,null,wnohang)) ==0) {
  23. Sends the Sigkill signal to the child process, regardless of whether the child process is blocked or processed, will end
  24. if ((Ret=kill (Pid,sigkill)) ==0) {
  25. printf ("Parent Kill Child%d!\n", PID);
  26. }
  27. }
  28. Wait child process, blocking mode
  29. Waitpid (pid,null,0);
  30. Exit (0);
  31. }
  32. }
Copy Code


Operation Result:

$./a.out
Child 9271 are waiting for signal ...
Parent Kill child 9271!



Note: About Kill (1) and kill (2)
Kill (1) refers to the use of the terminal command line, you can use the "Man 1 Kill" command query usage; Kill (2) refers to the function use, you can use the "Man 2 Kill" command query usage.

function alarm () and pause ()
The alarm () function sets a timer that, when specified by the timer, sends a SIGALRM signal to the process, and if this signal is ignored or not captured, the process that invokes the alarm function is terminated by default.
Each process can have only one timing time. If the timing time that was set for the process has not yet arrived when alarm is called, the remaining value of that timer time is returned as the value of the alarm function call. The pre-set timing time is replaced by the new value. If the new timing value is 0, the timer is canceled and the remaining value is returned.

The pause () function suspends the calling process until a signal is captured. The statement after pause executes only if a signal handler is executed and returned from it, and pause returns. Otherwise the process is terminated directly by default processing.

function header files and prototypes:
#include <unistd.h>
unsigned int alarm (unsigned int seconds);
int pause (void);

The code example does not set SIGALRM signal processing:

    1. #include <unistd.h>
    2. #include <stdio.h>
    3. #include <stdlib.h>
    4. #include <signal.h>
    5. int main ()
    6. {
    7. int Ret=alarm (5);
    8. printf ("Alarm return:%d.\n", ret);
    9. RET returns 0
    10. Sleep (3);
    11. Ret=alarm (5);
    12. printf ("Alarm return:%d.\n", ret);
    13. Blocks the current process until a signal is received
    14. We're going to get a alarm signal.
    15. Pause ();
    16. printf ("Wake up!\n");
    17. }
Copy Code

Operation Result:
$./a.out
Alarm return:0.
Alarm Return:2.
Alarm Clock


code example, set up the SIGALRM signal processing:

    1. #include <unistd.h>
    2. #include <stdio.h>
    3. #include <stdlib.h>
    4. #include <signal.h>
    5. Signal processing functions
    6. static void Alarm_handler (int signo)
    7. {
    8. printf ("Alarm signal receive!\n");
    9. }
    10. int main ()
    11. {
    12. Setting the capture signal
    13. Signal (Sigalrm,alarm_handler);
    14. int Ret=alarm (5);
    15. printf ("Alarm return:%d.\n", ret);
    16. RET returns 0
    17. Sleep (3);
    18. Ret=alarm (5);
    19. printf ("Alarm return:%d.\n", ret);
    20. Blocks the current process until a signal is received
    21. We're going to get a alarm signal.
    22. Pause ();
    23. printf ("Wake up!\n");
    24. }
Copy Code

Operation Result:
$./a.out
Alarm return:0.
Alarm Return:2.
Alarm signal Receive!
Wake up!


You can see the statement printf ("Wake up!\n") after the signal processing is set, after pause (), is executed to.

Linux signal signal usage explanation and precautions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.