Linux 2nd day

Source: Internet
Author: User
Tags signal handler sleep function terminates

Orphan process and zombie process

If the parent process exits first and the child process does not exit then the parent process of the child process becomes the init process. (Note: Any process must have a parent process)

If the child process exits first and the parent process does not exit, the child process must wait until the parent process captures the exit state of the child process to really end, otherwise the subprocess becomes a zombie process.

Orphan process

If the father process ends first, the subprocess will be tuogu to process number 1th.

The parent process registers the SIGCHLD signal and then in the callback function while (waitpid (0, NULL, Wnohang) > 0); Note that this semicolon must not be less.

Another way to avoid zombie processes

#include <signal.h>

Signal (SIGCHLD, sig_ign); Tell the kernel, this process to ignore SIGCHLD, please kernel brother help handle.

1. Why wait and Waitpid appear

SIGCHLD

When the child process exits, the kernel sends a SIGCHLD signal to the parent process, and the exit of the child process is an asynchronous event (the child process can terminate at any time the parent process runs)

When a child process exits, the kernel resets the subprocess to zombie state, a process called a zombie process that retains only the smallest number of kernel data structures so that the parent process queries the exit status of the child process.

The parent process can query the exit state of the child process with the Wait/waitpid function

Wait gets status post detection processing

Macro Definition Description

wifexited (status) Returns a non-0 value if the child process ends normally

Wexitstatus (status) Returns the child process exit code if wifexited nonzero

wifsignaled (status) child process terminates because of a capture signal, returns a value other than 0

Wtermsig (status) if wifsignaled nonzero, returns the signal code

wifstopped (status) Returns a non-0 value if the child process is paused

Wstopsig (status) if wifstopped nonzero, returns a signal code

To wait for the end of a particular process

Waitpid (pid_t pid, int *status,int options)

The interpretation of the p I d parameter for Waitpid is related to its value:

pid = =-1 waits for any child process. So waitpid is equivalent to wait in this function.

pid > 0 waits for its process I D and p I d to be equal to the child process.

pid = = 0 waits for its group I d to be equal to any of the child processes that call the process's group I d. In other words, the process is in the same group as the caller process.

pid <-1 waits for any subprocess whose group I D equals the absolute value of p I D .

Wait and waitpid differences and connections

Before a child process terminates, wait causes its callers to block, and Waitpid has a selection that allows the caller to not block.

Waitpid does not wait for the first terminating child process-it has several choices that can control the specific process it waits for.

In fact, the wait function is a special case of the Waitpid function.

Abort ()//will issue a signal No. 6th

Session period: is a collection of one or more process groups, typically a session period begins with the user's logon and terminates when the user exits. During this time, all processes run by the user belong to this session period.

Interrupt

Interrupts are system responses to asynchronous events ()

Interrupt Signal

Interrupt Source

Site information

Interrupt handlers

Interrupt Vector Table

Asynchronous event Response: Process Execution code can be interrupted at any time, then go to execute exception handler

Interruptions in life and interruptions in computer systems

4) Other concepts of interruption

The Interrupt vector table holds the entry address of the interrupt handler.

The number of interrupts is fixed, and the interrupt vector table is initialized when the operating system starts.

Interrupt has priority (someone knocks, someone calls, has priority)

Interrupts can be masked (Zhang San can block the phone).

Signal Name Description

SIGABRT Process stops running 6

SIGALRM warning Bell

SIGFPE Computational Exceptions

SIGHUP system hangs up

Sigill illegal Instructions

SIGINT Terminal Interrupt 2

SIGKILL Stop process (this signal cannot be ignored or captured)

Sigpipe writing data to a pipeline without readers

SIGSEGV Invalid memory segment access

Sigquit Terminal Exit 3

SIGTERM termination

SIGUSR1 user-defined signal 1

SIGUSR2 user-defined signal 2

SIGCHLD child process has stopped or exited

Sigcont If it is stopped continue execution

SIGSTOP Stop Execution

SIGTSTP Terminal Stop signal

Sigtout a background process request for a write operation

Sigttin background Process requests for read operations

Process to the signal of three kinds of corresponding

Ignore signal

No action is taken and two signals cannot be ignored:SIGKILL (signal 9th) and Sigstop.

Think 1: Why the process cannot ignore Sigkill, sigstop signals. (If the application can ignore these 2 signals, system management cannot kill, halt the process, and the system cannot be managed.) )。 SIGKILL (signal number 9th) and Sigstop signals cannot be captured.

Capture and process signals

The kernel interrupts the code being executed and goes to execute a previously registered handler.

Perform the default action

The default action is usually to terminate the process, depending on the signal being sent.

Signal Signal Installation function

Function prototypes: __sighandler_t signal (Intsignum, __sighandler_t handler);

The return value, if successful, returns the previous behavior of the signal

Unreliable signal PK reliable signal

Unreliable signals are the first 32 signals and do not support queueing. In the fast send can cause loss, because in the process PCB control signal set of outstanding signals, is not queued, the arrival of multiple same-kind signals, there will only be a same kind of signal in the pending set.

Reliable signal

With the development of time, it is proved necessary to improve and expand the original mechanism of signal. As a result, later versions of Unix have been studied in this area, trying to achieve "reliable signals". Since there are many applications for the previously defined signals, it is not good to make any changes, and eventually we have to add some new signals and define them as reliable signals at the outset, which support queuing and will not be lost. At the same time, the signal transmission and installation also appeared a new version: Signal transmission function sigqueue () and Signal installation function sigaction ().

Some notes on the sleep function

1) Sleep function, let the process of sleeping.

2) can be interrupted by the signal, and then after processing the signal function, no longer sleep. Execute code directly down

3) The return value of the sleep function, which is the remaining number of seconds

Raise

Raise

Send a signal to yourself. Raise (SIG) is equivalent to Kill (Getpid (), SIG);

Killpg

Sends a signal to the process group. KILLPG (Pgrp, SIG) is equivalent to Kill (-pgrp, SIG);

Sigqueue

Sends a signal to the process, supports queuing, and can be accompanied by information.

Pause () function

Set the process to an interruptible sleep state. It then calls the kernel function schedule (), which causes the Linux process scheduler to find another process to run.

Pause causes the caller process to hang until a signal is captured

Alarm function, set an alarm delay send signal

Tells the Linux kernel to send the SIGALRM signal after n seconds;;

reentrant function Concept

To enhance the stability of the program, the Reentrant function should be used in the signal processing function.

A reentrant function is a process that can be called by multiple tasks, and the task does not have to worry about whether the data will go wrong when it is called. Since the process receives the signal, it jumps to the signal handler to proceed. If a non-reentrant function is used in a signal-processing function, the signal-processing function may modify data that should not be modified in the original process, so that the process may have unpredictable consequences when it returns to execution from the signal handler function. The non-reentrant function is considered an unsafe function in the signal processing function.

Most of the functions that meet the following conditions are non-reentrant: (1) using static data structures such as GetLogin (), Gmtime (), Getgrgid (), Getgrnam (), Getpwuid (), Getpwnam (), and so on (2) when the function is implemented, The malloc () or free () function is called, and (3) the implementation uses a standard I/O function

The representation of the signal in the kernel

the processing action of the signal is called the signal recursion (Delivery), the signal from the generation to the state between the recursion, called Signal pending (Pending).

A process can choose to block (block) a signal. When the blocked signal is generated, it remains in the pending state until the process has unblocked the signal and executes the recursive action.

Drawing

When a signal is sent to a process, the Process control block PCB controls the direction of the signal, the pending set (readable only, not writable), the blocking set (readable writable) are 64 digits, because there are 64 signals, each bit corresponds to a signal, a signal to pass through these two sets to arrive

The initial state of the pending set is all 0, the signal first enters the pending set, the corresponding bit of the pending set becomes 1, and then the blocking bit, if the blocking bit is 1, then the signal cannot pass, it has been in the pending set, this is called the pending state, once the blocking bit becomes 0, the signal is passed, the pending set has not

The signal is finally determined by the program how to handle (ignore, catch, default behavior), processing when the pending set becomes 0, can receive new signals.

When a signal is unblocked in a signal processing function, only the pending is cleared 0

Signal Set operation function (state Word representation)

#include <signal.h>

Intsigemptyset (sigset_t *set); Empty the signal set 64bit/8=8 bytes sigset_t is a 64-bit number

Intsigfillset (sigset_t *set); Complete the signal set in 1.

Intsigaddset (sigset_t *set, Intsigno); According to Signo, set the corresponding signal concentration to 1

Intsigdelset (sigset_t *set, Intsigno); According to Signo, set the corresponding signal concentration to 0

Intsigismember (constsigset_t *set, Intsigno);//Determine if Signo is in the signal set

Sigprocmask read or change the signal mask status word (block) of a process

#include <signal.h>

int sigprocmask (int how, const sigset_t *set, sigset_t *oset);

Function: Read or change the signal screen word of the process.

Return Value: 0 if successful, or 1 if there is an error

Sigpending get signal Pending status Word (pending) information

#include <signal.h>

int sigpending (sigset_t *set);

sigaction function

The signal registration function, like signal, is only more powerful.

int sigaction (int signum,const struct sigaction *act,const struct sigaction *old);

sigaction Structural Body

The second parameter is most important, including the processing of the specified signal, the information transmitted by the signal, which functions should be screened out during the execution of the signal processing function, etc.

structsigaction {

void (*sa_handler) (int); Signal processing program does not accept additional data

void (*sa_sigaction) (int, siginfo_t *, void *); Signal Processing program can accept additional data, and sigqueue with the use of

sigset_t Sa_mask; Which signals are blocked during the execution of the signal processing function The Sa_mask type is the same as the unregistered signal set. But you don't need sigprocmask.

int sa_flags; The behavior that affects the signal sa_siginfo to accept the data

void (*sa_restorer) (void); Abandoned

};

Note 1: The callback function handle Sa_handler, sa_sigaction can only be selected.

Sigqueue new signal sending function, more powerful function.
    struct Sigaction Act;    Union Sigval  Mysigval;        Mysigval.sival_int = 111;    Sigemptyset (&act.sa_mask); Signal processing does not block other signals,    act.sa_flags = sa_siginfo;//means sending data plus new content    act.sa_sigaction = msigaction;//callback function Assignment    Sigaction (SIGINT, &act, NULL);  Register Signal        Sigqueue (Getpid (), SIGINT, mysigval);//Send Signal

  

Sigqueue () passes more additional information than kill (), but Sigqueue () can only send a signal to a process and not send a signal to a process group.

Linux 2nd day

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.