Linux _ signal operations

Source: Internet
Author: User

Linux _ signal operations

Create two sub-processes;
Step 1: Write the mytest.txt file,
Write once every 5 seconds,
The time when the data is written.
Step 2: Read the file mytest.txt,
Read every 5 seconds,
Read and print the latest time written in the file.
All read/write operations are protected by file locks.
Main. c

Time_t currtime;
Time (& currtime );
Char * time_string = ctime (& currtime );

Signal
What is a signal?
A signal is an event.
Custom signals are not supported. All signals are predefined by the system.

Who generates the signal?
1) The shell terminal generates the corresponding signal based on the current error (segment error, invalid command, etc.)
For example:
Socket communication or pipeline communication,
If the read end is disabled,
Perform write operations (or send data ),
The process that executes the write operation receives the SIGPIPE signal.
(Indicating pipe rupture)
Default behavior of the signal: terminate the process.

2) use the kill or killall command to generate a signal on the shell terminal.
Instance: main1.c
./A. out &
Kill-HUP 13733/* Send SIGHUP to a process whose PID is 13733 */
3) Call the kill system call in the program code to generate a signal

Description of signal names

The SIGABORT process terminates abnormally.
SIGALRM timeout alarm
SIGFPE floating point operation exception
SIGHUP connection HANGS UP
Invalid SIGILL command
SIGINT terminal interruption (Ctrl + C will generate this signal)
SIGKILL * terminate the process
SIGPIPE writes data to a pipeline without a read Process
Exit the SIGQUIT terminal (Ctrl + \ will generate this signal)
Invalid SIGSEGV memory segment access
SIGTERM termination
SIGUSR1 * User-Defined signal 1
SIGUSR2 * User-Defined Signal 2
-------------> If the above signal is not captured, the process will terminate after receiving it!
The SIGCHLD sub-process has stopped or exited.
SIGCONT * allows the paused process to continue execution
SIGSTOP * stop execution (that is, "pause ")
SIGTSTP Suspension
SIGTTIN background process attempts to read

SIGTTOU background process attempted to write

Signal capture
Signal capture means to execute a specified function after receiving a certain signal.
Note: SIGKILL and SIGSTOP cannot be captured,
That is, the response actions of these two signals cannot be changed.

SIGNAL INSTALLATION
1) Use signal
Usage: man 2 signal

Typedef void (* sighandler_t) (int); sighandler_t signal (int signum, sighandler_t handler); Note: The return type of signal, and its second parameter, parameter 2 of the function pointer type can go to the following special values: SIG_IGN ignores the signal SIG_DFL to restore the default behavior instance: main2.c changes the terminal interrupt signal behavior and thus the process cannot be ended! Only one other signal can be sent to the process through other terminals to terminate it # ps ax | grep. /. out // query process no. # default act of kill-HUP process no. Recovery signal main3.c when SIG_DFL is used, SIG_DFL can be restored only when custom behavior is called for the first time, if it is captured multiple times in a row, you are not sure.

2) use sigaction
Difference between sigaction and signal:
Sigaction is more "robust" than signal. We recommend that you use sigaction.

Usage: man 2 sigaction

Structure struct sigaction
Struct sigaction {
Void (Sa_handler) (int );/Signal response function */
Sigset_t sa_mask;/* blocked Signal Set */
Int sa_flags;/* When sa_flags contains SA_RESETHAND, this signal is received and called
* After the specified signal processing function is executed, reset the Response Behavior of the signal to the default behavior SIG_DFL */
...
}

Supplement: When sa_mask contains A signal A, if this signal A occurs during the execution of the signal processing function, the signal A is blocked (that is, the signal should not be sent temporarily ), until the signal processing function is executed. That is, after the signal processing function is executed, it then responds to the signal A instance: main4.c use sigaction to change the Response Action: Use sigaction to rewrite main2.c main5.c use sigaction to restore the default action and use sigaction to rewrite main3.c

Signal sending
Signal Transmission Method:
Use shortcuts to generate signals on shell Terminals
Use the kill and killall commands.
Use kill and alarm Functions

1) Use the kill Function
Sends a specified signal to a specified process.
Usage: man 2 kill
Note:
"Permission" is required to send signals to a specified process ":
Normal user processes can only send signals to other processes of the user.
The root user can send signals to all users' processes.
Kill failed
-1 is returned when a failure occurs.
Cause of failure:
Insufficient Permissions
Signal does not exist
The specified process does not exist.

Instance: main6.c creates a sub-process and outputs the string "child process work!" per second! "The parent process waits for user input. If the user presses character A, it sends the signal SIGUSR1 to the child process. The output string of the child process is changed to uppercase. If the user presses character, sends the signal SIGUSR2 to the sub-process, and the output string of the sub-process is changed to lowercase.

Instance: main7.c
"Alarm Clock"
Create a sub-process
The sub-process sends a SIGALRM to the parent process after five seconds.
When the parent process receives the SIGALRM signal, it "makes an alarm" (print the simulation)

2) use the alarm function
Purpose: Send a SIGALRM signal to the process itself within the specified time.
Usage: man 2 alarm
Note: The unit of time is second"
The actual alarm time is larger than the specified time.
If the parameter is 0, the set alarm is canceled.
If the alarm time is not reached and alarm is called again, the alarm will be timed again.
Each process can only use one alarm clock.

Return Value: Failed: Return-1 success: return the remaining time (seconds) of the last alarm. instance: "alarm" main8.c rewrite main7.c with alarm

3) use raise
Sends signals to the process itself.
Prototype: int raise (int sig)

Send multiple signals:

A process is executing an operation function corresponding to a signal (the installation function of the signal). If the process receives the same signal (the same signal value) multiple times ), then: if the signal is an unreliable signal (<32), it can only respond once again. If the signal is a reliable signal (> 32), it can respond multiple times (no omission ). However, all of them must wait until the response function is executed to respond to the next time.

A process is executing an operation function corresponding to a signal (the installation function of this signal ),
If the process receives another signal (signal with different signal values) at this time, then:
If the signal is included in the sa_mask (signal shielding set) of the current signaction,
This signal is not processed immediately.
The signal processing function is not executed until the current signal processing function is executed.
Otherwise:
Immediately interrupt the current execution process (if you are asleep, such as sleep, you will be immediately woken up)
And execute this new signal response.
After the new response is executed, it is returned to the original signal processing function for execution.

Example: main4_2.c

Signal Set
1). What is a signal set?
Signal Set, represented by the sigset_t type, is essentially an unsigned long integer.
Used to represent a set containing multiple signals.

2) basic operations on the Signal Set
Sigemptyset clears the Signal Set
Sigfillset fills all defined signals into the specified Signal Set
Sigdelset deletes the specified signal from the specified Signal Set
Sigaddset adds the specified signal from the specified Signal Set

Sigismember checks whether the specified signal is in the specified signal set. If yes, 1 is returned. If no, 0 is returned.-1 is returned. For details, see man.

3) "signal shielding word" of the process"
A process's "signal shielding word" is a signal set
If you want the target process to send a signal,
The target process will not capture the signal, that is, it will not execute the processing function of the signal.
When the signal shielding word of the process no longer contains the signal, it will capture the signal that has already been received (execute the corresponding function)

Use sigprocmaskint sigprocmask (int how, const sigset_t * set, sigset_t * oldset) to modify the "signal shielding word" of a process. Parameter: how: SIG_BLOCK: add the signal in the set parameter to the signal shielding word. SIG_UNBLOCK: remove the signal in the set parameter from the signal shielding word SIG_SETMASK. set the signal in the set parameter to the signal shielding word. oldset returns the original signal. shielding example: main4_3.c

4) Obtain unprocessed signals
When a process's signal shield signal occurs, the signal will not be responded by the process,
You can use the sigpending function to obtain the signals that have occurred but are not processed.

Usage: man sigpending
Return Value: 0 if the request is successful.
-1 is returned if the request fails.

5) blocked waiting signal
(1) pause
Blocks the process until any signal occurs.

(2) sigsuspend
Set the signal shielding characters with the specified parameters, and then wait for the signal to reverse generate when blocking.
That is, only waiting for signals other than the shielded characters

6) use the sa_flags in the sigaction Structure
The parameters of the sigaction function use struct sigaction.
The struct sigaction structure has the sa_flags flag:
After the signal processing function specified by SA_RESETHAND is executed,
Reset the Response Behavior of the signal to the default behavior SIG_DFL.
When the SA_NOCLDSTOP sub-process is stopped, no SIGCHLD signal is generated.
SA_NODEFER by default, when a signal processing function is being executed,
The signal will be added to the signal shielding word of the process,
To prevent the current signal processing function from being processed,
If this signal occurs again, the signal processing function will run again.
After the signal processing function is executed, delete the signal from the signal shielding word of the process.

The reason for the above default settings: if the signal processing function is "reentrant", it will be interrupted and re-executed, and an error will occur! The above default settings can avoid repeated occurrences of the same signal, so that the signal processing function can be executed repeatedly without completion. If SA_NODEFER is used, the signal will not be added to the signal shielding word. SA_RESTART: by default, if an interrupted Linux System Call receives a signal during execution, the system call will return an error and set errno to EINTR. If SA_RESTART is used, after the signal processing function is executed, the system call interrupted by the signal will be re-executed, rather than simply returning an error.

Function "reentrant"
Only the "reentrant" function can be called in signal processing functions.
Because the signal processing function may be interrupted during execution.

Function that cannot be reentrant after the completion of the previous operation,
When you run it again, a problem may occur!

For example, the printf function cannot be reentrant.
Therefore, printf should not be called in signal processing functions.

Solution: In the signal processing function, set a flag to judge the flag outside of the signal processing function, and use printf according to the status of the flag.

Appendix:
Linux signal:
Unreliable Signal
1) SIGHUP
2) SIGINT
3) SIGQUIT
4) SIGILL
5) SIGTRAP
6) SIGABRT
7) SIGBUS
8) SIGFPE
9) SIGKILL
10) SIGUSR1
11) SIGSEGV
12) SIGUSR2
13) SIGPIPE
14) SIGALRM
15) SIGTERM
16) SIGSTKFLT
17) SIGCHLD
18) SIGCONT
19) SIGSTOP
20) SIGTSTP
21) SIGTTIN
22) SIGTTOU
23) SIGURG
24) SIGXCPU
25) SIGXFSZ
26) SIGVTALRM
27) SIGPROF
28) SIGWINCH
29) SIGIO
30) SIGPWR
31) SIGSYS

Real-time signal (reliable signal)
34) SIGRTMIN
35) SIGRTMIN + 1
36) SIGRTMIN + 2
37) SIGRTMIN + 3
38) SIGRTMIN + 4
39) SIGRTMIN + 5
40) SIGRTMIN + 6
41) SIGRTMIN + 7
42) SIGRTMIN + 8
43) SIGRTMIN + 9
44) SIGRTMIN + 10
45) SIGRTMIN + 11
46) SIGRTMIN + 12
47) SIGRTMIN + 13
48) SIGRTMIN + 14
49) SIGRTMIN + 15

50) SIGRTMAX-14
51) SIGRTMAX-13
52) SIGRTMAX-12
53) SIGRTMAX-11
(54) SIGRTMAX-10
55) SIGRTMAX-9
SIGRTMAX-8 (56)
57) SIGRTMAX-7
SIGRTMAX-6 (58)
(59) SIGRTMAX-5
SIGRTMAX-4 60)
SIGRTMAX-3 (61)
62) SIGRTMAX-2
3) SIGRTMAX-1
64) SIGRTMAX

No 32 and 33 are defined

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.