Linux programming-Processes and Signals (chapter 11th)

Source: Internet
Author: User

11.4.1 send signal the process can send a signal to other processes, including itself, by calling the kill function. If the program does not have permission to send the signal, the call to the KILL function will fail. A common cause of failure is that the target process is owned by another user. This function, with the same name as the shell command, accomplishes the same function, and it is defined as follows:
#include <sys/types.h> #include <signal.h>int kill (pid_t pid, int sig);
The KILL function sends a signal given by the sig to the process specified by the parameter PID given by the process number, and succeeds it returns 0. To send a signal, the sending process must have the appropriate permissions, which usually means that even a process must have the same user ID.
The kill call returns 1 on failure and sets the errno variable. The reason for the failure may be: the given signal is invalid, the sending process has insufficient permissions, and the target process does not exist.
The signal provides a useful alarm function. The process can send a SIGALRM signal after a predetermined time through the alarm function.
#include <unistd.h>
unsigned int alarm (unsigned int seconds);
The alarm function is used to arrange for sending a sigalrm signal after seconds seconds, but due to the delay of processing and the uncertainty of the time schedule, The actual alarm time will be slightly longer than the pre-arranged one. Setting the parameter seconds to 0 cancels all alarm requests that have been set. If you call the alarm function again before you receive the SIGALRM signal, The alarm clock starts again. Each process can have only one alarm. The return value of the alarm function is the remaining second of the previously set alarm time, and returns 1 if the call fails.
To illustrate the work of the alarm function, simulate its effect by using fork,sleep and signal. The program can start a new process. It is designed to send a signal at some point in the future.
Writing a program ALARM.C
#include <sys/types.h> #include <signal.h> #include <stdio.h> #include <unistd.h> #include < stdlib.h>static int alarm_fired = 0;void ding (int sig) {alarm_fired = 1;} /* In the main function, tell the child process to send a SIGALRM signal to its parent process after waiting for 5 seconds */int main () {pid_t pid;printf ("Alarm application starting\n");p id = fork (); Switch (PID) {case-1:/* Failure */perror ("fork failed"); exit (1); case 0:/* Child */sleep (5); Kill (Getppid (), SIGALRM); Exit (0);} /* The parent process arranges the work of capturing the SIGALRM signal through a signal call and waits for it to arrive */printf ("Waiting for alarm to go off\n");(void) signal (SIGALRM, ding); Pause (); if (alarm_fired) printf ("ding!\n");p rintf ("done\n"); exit (0);}
When you run the program, it pauses for 5 seconds, waiting for the alarm to be simulated.
This program uses a new function, pause (), which is very simple to suspend the execution of the program until a signal appears. When the program receives a signal, the pre-programmed signal processing function will start to run and the program will return to normal execution. The pause function is defined as follows:
#include <unistd.h>int pause (void)
When it is interrupted by a signal, it returns 1 (if the next received signal does not cause the program to terminate) and sets the errno to Eintr. A more common practice when waiting for a signal is to use the Sigsuspend function that will be described later.
The alarm simulator starts a new process with a fork call, and the child process sends a SIGALRM signal to its parent process after sleeping for 5 seconds. The parent process pauses until it has been scheduled to capture the SIGALRM signal until a signal is received. printf is not used directly in the signal processing function, Instead, the output of the message is completed by setting a flag in the function and then checking the flag in the main function.
Using signals and suspending program execution is an important part of Linux programming. This means that the program does not need to be always executing. The program does not have to endlessly check whether an event has occurred in a loop, instead it can wait for the event to occur. This is especially important in a multi-user environment with only one CPU, Processes share a single processor, and a busy wait can have a significant impact on the performance of the system. The use of signals in the program poses a special problem: "What happens if a signal occurs during the execution of a system call?" The answer is quite unsatisfactory, "depending on the circumstances." In general, it is only necessary to consider slow system calls, such as reading data from a terminal, and returning an error if a signal appears when the system calls to wait for data. If you start using the signal in your program, It is important to note that some system calls fail because they receive a signal, which may not be considered before the signal processing function is added.
You must be very careful in writing the code for the signal part in your program, because there are a variety of "race conditions" in the program that uses the signal. For example, if you want to call pause to wait for a signal, the signal appears before you call pause. Causes the program to wait indefinitely for an event that does not occur. These race conditions are a time-critical issue, so always be careful when checking and signaling related code.
a robust signal interface
Signal and its related functions have been introduced in-depth to generate and capture signals, as they are common in traditional UNIX programming. But the X/open and UNIX specifications recommend an update that is more robust to interface: Sigaction. It is defined as follows:
#include <signal.h>int sigaction (int sig, const struct sigaction *act, struct sigaction *oact);
The sigaction structure is defined in the file signal.h, and it is defined as the action that should be taken after receiving the signal specified by the SIG. The structure should include at least a few members:
void (*) (int) sa_handler/*        function, Sig_del or sig_ignsigset_t sa_mask/                * signals to block in Sa_handlerint Sa_ Flags/                    * Signal Action modifiers
The Sigaction function sets the action associated with the signal sig. If oact is not a null pointer, Sigaction will write the previous action on the signal to the position it points to. If the act is a null pointer, the Sigaction function does not need to make any more settings. Otherwise, the action on the specified signal is set in this parameter.
Like the signal function, the Sigaction function returns 0 on success, and 1 when it fails. If the given signal is invalid or attempts to capture or ignore a signal process that is not allowed to be captured or ignored, the error variable errno will be set to Einval.
In the sigaction structure that the parameter Act points to, Sa_handler is a function pointer that points to the signal processing function that will be called when the signal sig is received. It is equivalent to the parameter func passed to the function signal as seen earlier. You can love that sa_. The handler field is set to the special values Sig_ign and SIG_DFL, which indicate that the signal is ignored or the signal is processed to the default action.
The Sa_mask member specifies a set of signals that, before invoking the signal processing function pointed to by Sa_handler, The signal set will be added to the signal screen word of the process. This is a set of signals that will be blocked and will not be passed to the process. Setting the signal screen Word prevents the signal that was seen earlier from being received at the end of its processing function. Use the Sa_mask field to eliminate this race condition.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Linux programming-Processes and Signals (chapter 11th)

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.