Linux and process signals

First, the process

  

Procedures and processes

  Program is a binary file, static stored on disk, not take up memory and CPU resources; it will have a process running, the process is dynamic, will take up some memory and CPU resources.

  A physical cpu can only run one process at the same time, multi-task on multiple pieces of physical cpu can really sense. The reason why people will be able to simultaneously generate system "illusion" of running multiple processes, because the process of switching between the CPU implemented in a very short period of time.

  On Linux, the system is determined by the scheduler to execute a process. When the process is running, depending on its priority, the lower the priority value, the higher the priority, the faster the selected scheduler. We can change the nice value of the process to change its priority value. Important need to let the process is completed as soon as possible, that is, need more time to perform some CPU assigned to it. The first minor back slightly.

  In the case of the kernel can force time slice on the process runs out of CPU to recover the right to use, and next to the CPU scheduler process selected, this approach is called "preemptive multi-tasking." This time before a process has not finished running was recovered right to use the CPU, but at some time in the future they will be selected scheduler, so save the environment when running kernel will suspend each process down (save in the kernel memory occupied), which is known to protect the site. When the scheduler is selected again to resume operation, the operating environment will save the original loaded on the CPU to continue, which is called the recovery site.

  After the scheduler selected by a process, the task will be the bottom of the switch, which is the context switch. Switch should not be too frequent and too often lead to the protection and restoration of the site for too long and affect the efficiency of the CPU, because this time the CPU is not working; switch should not be too slow, too slow a process to lead to the next a long time to "host", for example, you execute the command cd, long time to get a response, which is obviously unreasonable.

  CPU unit of measurement is the time, the memory unit of measurement is space. CPU percentage value is equal to "process CPU time / CPU total time."

  

Parent and child processes

  Derived from the parent process child process. The system will assign to each process a unique PID, or the calling program execution environment in the process of A, B process generated by this program is the child process. PID PPID sub-process is that it is the parent process, you can view information about the ps command. The parent process may be derived plurality of sub-processes, CentOS 6 is the parent of all processes init, the parent of all processes is 7 CentOS systemd. Linux on the way to create a process in three ways:

  • way fork : fork is the copying process, it will be copied to the copy of the current process of so-called child process, the parent and child is the same available resources, including memory resources. But father and son process is independent of each other, they are two instances of a program.
  • exec way to load a new program (substitution) in the case exec is to load another program to replace the current process, that is, without creating a new process: When you create a new process, in order to ensure the safety of the process, the current process will be a first fork and exec calls on this basis, to load new programs replace the child process. For example executed in bash cp command will first fork out a bash, and then load the exec cp program covering child bash process becomes cp process. But we know that will copy all memory pages when the fork process, but initialization address space using the exec load new programs, which means that copy the action is entirely superfluous, it would certainly affect the efficiency, because the data address space is also ranging from a few megabytes to hundreds of megabytes. Copy-on-write (Copy On Write, COW) technologies emerge perfect solution to this problem (COW would say the following)
  • clone manner : How it works the same clone and fork, but the clone out of the child and the parent process is not independent, and it will be the parent process share some resources, you need to specify what resources are shared when the clone process.

  In general, the process is independent of each other between the brothers is not visible, but the data transfer between the two through the "pipeline" can be achieved.

  

Copy-on-write technology

  Before fork exec later, the kernel creates a new child process virtual space structure, they are copied to the parent virtual spatial structure, but not for these segments (text segment, data segment, stack, stack) allocation of physical memory, they are read-only shared physical memory space of the parent process, when there are changes to the parent and child in the corresponding period of behavior, then the corresponding segments for the child process to allocate physical space. Bluntly put, is only an empty structure to fork child process, the actual physical space in read-only mode for shared use of the parent process, the child process when the corresponding period of the change will not be replicated resources corresponding segment of the parent process, with take what what, do not take. It is divided into two cases:

  • Not running after exec fork. The kernel is a sub-process data segment, a stack segment corresponding physical space allocation of the sub-process is independent of the parent process. The text segment is shared physical space of the parent process (both code is the same).
  • After running exec fork. That is to load a new program replaces the original child process, then the body of the code section must be changed, it will also allocate a separate physical space.

  

Process State

  1. The new status: that the new process
  2. Ready state: Process is selected in the waiting queue, waiting for the scheduler.
  3. Run state: scheduler to select it, then start running.
  4. Sleep mode: The process is running stations because of the need to wait for an event (IO wait wait or signal) appears unenforceable, then goes to sleep. Sleep state is divided into interruptible sleep and uninterruptible sleep. Can interrupt sleep allowed to receive outside signals and signal the kernel to wake up the process, we captured with the ps or top command most of them can interrupt sleep; not only interrupt sleep wake-up signal by the kernel, mainly when interacting with the hardware, For example, when viewing the file contents with cat, it is not to be interrupted, do not know anyone encountered cat can only see part of the file content.
  5. Termination state: the process has finished running, return the exit code.
  6. Zombie state: Process has been terminated, but not enough time to remove items kernel process list.

  Mode conversion between states:

  • New state -> ready state: new process to join the waiting queue.
  • Ready state -> Run state: the process is waiting queue is selected scheduler.
  • Runnable -> Sleep state: for example, when you do not add yum -y install the software parameters, prompted yes, the moment the process has entered sleep mode, you need to wait until the signal to enter the ready state is yes.
  • Sleep mode -> ready state
  • Runnable -> ready state: the kernel allocates CPU time slice expires, or is preempted by higher-priority process.
  • Operating mode -> termination state
  • Termination state -> state zombies

  For example analysis process state transition process

  Or to the cp command as an example. In the current environment, execute the cp command bash, bash first fork a child process, then the sub-exec bash on the program loaded cp, cp child process into a wait queue, due to the knock command at the command line, so the higher the priority, scheduling is quickly select it. During execution of the child process cp, the parent process bash will go to sleep waiting to be awakened (the process of waiting), not at the moment bash and human interaction. When the cp command is complete, it will inform its exit status of the parent process, the copy succeeds or fails, then disappeared out of their own cp process, the parent process bash wake up again into the waiting queue, and the bash has gained cp exit status. According to the state code of this "signal", the parent bash knew the child process has been terminated, the notice to the kernel, the kernel receives cp process entries deleted after notification process list. At this point, the entire process is completed normally cp.

  Cp if this is a child process of copying large files, a copy cpu time slice can not be completed, then a cpu time slice depleted when it enters the queue.

  If the child process when cp copy files, destination files have the same name, the default will be asked whether to overwrite it waits yes or no inquiry signal is issued, it goes to sleep (interruptible sleep), when the keyboard knock on yes or no signal when to cp, cp received signal into the ready state from a sleep state, waiting for it to finish scheduling class selected cp process.

  When cp replication, disk and it needs to interact in a short process and interaction of hardware, cp will be in uninterruptible sleep.

  If cp end of the process, but the end of the process there has been some kind of accident, making the bash parent does not know it's over (cp command is not possible for this situation), then bash will not notice the kernel recovery process list the entry cp, cp At this point it becomes a zombie process.

  

Process type and sub-shell

  • Foreground process: general commands (such as cp command) will fork child process to execute when executed, during the execution of a child process, the parent process into sleep, these are foreground processes.
  • Background process: at the end of the command with "&" symbol, after executing command returns the parent process immediately and return the pid jobid and background processes, so the parent process not go to sleep
  • bash built-in commands: This command is very special, the parent process does not create a child process (bash will not create a child bash) execute these commands, but executed in the current bash. But if the built-in commands in the pipeline, then the built-in commands and command belong to a pipe in front of the group process, this situation will create a child process.

  Two special script invocation: exec and Source . exec loader is to replace the current process, such as command line cp command, would like to fork a child bash, and then use the exec cp program to load replacement sub-bash, will be sent after the implementation of the exit status to the parent bash, this can be considered "sub-shell" withdrew; and source will not turn sub-shell, directly in the current shell script calling and do not quit after the completion of the current shell, so the script is finished loading environment variable will take effect immediately in the current shell.

  The process execution will return into the background and process jobid pid, we can use the jobs command to view processes running in the background. If you want to quote jobid,% must be added in front, such as "kill -9% 1". Another way is to manually add the background by pressing CTRL + Z keys, which can be running in the process of accession to the background, but this added to the background processes running in the background will be suspended.

[root@template ~]# sleep 10s &
[1] 13225
[root@template ~]# jobs -l
[1]+ 13225 Running                 sleep 10s 
    # -l:显示进程的PID
    # -r:显示处于running状态的jobs
    # -s:显示处于stopped状态的jobs
[root@template ~]# sleep 20s
^Z[1]   Done                    sleep 10s

[2]+  Stopped                 sleep 20s
[root@template ~]# jobs 
[2]+  Stopped                 sleep 20s

  From the above examples can be seen behind jobid have a "+" denoted by "+" indicates that the task execution, "-" indicates that the task scheduler is selected to be executed next, the third task is not started from the then marked. Combined with the state of the task of view, the status is "running" no "+" means in the waiting queue; "running" of "+" indicates being performed; "stopped in sleep state."

  The job or into the background to the foreground, you can use fg and bg commands, strictly speaking, it is to run the state into the foreground and background, even if the original task was stopped state. Format fg | bg% jobid, the operation is not specified jobid is currently with the task of "+".

[root@template ~]# vim 123 &
[1] 13328
[root@template ~]# jobs 
[1]+  Stopped                 vim 123
[root@template ~]# fg %1
vim 123
~ 

  Use disown command directly out of a job from the job table, not the end of the task. After removal and job table, hanging in the task init / systemd process, it does not rely on the terminal.

disown [-ar] [-h] [%jobid ...]
   # -h:指定该选项,将不从job table中移出job,而是将其设置为不接受shell发送的sighup信号。
   # -a:如果没有指定jobid,表示对Job table中的所有job进行操作。
   # -r:如果没有指定jobid,表示只对running状态的job进行操作
[root@template ~]# sleep 50s &
[1] 13303
[root@template ~]# jobs 
[1]+  Running                 sleep 50s &
[root@template ~]# disown %1
[root@template ~]# jobs
[root@template ~]# ps -ef | grep [s]leep
root      13303  13185  0 19:42 pts/2    00:00:00 sleep 50s
[root@template ~]# ps -ef | grep [1]3185
root      13185  13181  0 19:02 pts/2    00:00:00 -bash

  

Process type and sub-shell

  Work we may encounter operational database backup, the backup time may be a long time, but soon off work, if you turn off the terminal, backup is suspended. So you should use a backup method back from the terminal. Note that the above "&" Although he is in the background, but is associated with the terminal with it, when you quit, jobs will disappear. I really want to disassociate with the terminal needs to be used in conjunction with the nohup. Another method is to screen, which I'm not familiar commands, which do not write.

[root@template ~]# nohup sleep 50s &

  

Second, the signal

  Linux supports a variety of signals, the signals they begin with SIG string is the real name of the signal SIG string signal as well as the corresponding value is the value of real understanding of the operating system. However, as many signals on different computer architectures of different values ​​(eg CTRL + SIGSTP signal there are three values ​​of Z sent 18,20,24), it is unique, it is best to specify its character name in signal numerical uncertainty .

  

Common Signal

Signal Value Comment
Sigःuf 1 When the terminal exit, in the process of this terminal will be terminated
SIGQUIT 3 Kill process signals from the keyboard
SIGKILL 9 Force kill process
SIGUSR1 10 User-defined signal 1
SIGUSR2 12 User-defined signal 2
SIGCHLD 17 The signal is sent to inform the parent that they have completed, the parent process receives a signal to tell the kernel cleanup process list. This signal can be lifted zombie process
SIGCONT 18 This transmission signal is stopped so that the process enters running, the signal is mainly used for jobs, e.g. fg and bg command signal will be sent to the
SIGSTOP 19 The process receives a status signal will enter the stopped
SIGTSTP 20 This signal can be ignored is the process stop signal (CTRL + Z)

  

Sigःuf

  When the control terminal exit, sighup will send a signal to the terminal in the process, so the shell process running on the terminal, other common processes and tasks will receive sighup signal caused the process to terminate. Several ways to change the behavior of the terminal due to interrupt transmission sighup caused the child process is also ended, just to introduce more common in three ways:

  • Use nohup & ignore all the way SIGHUP signal
  • The command to be executed in the sub-shell into the background, for example, "(sleep 10s &)"
  • Use disown -h sighup set signal is not sent by the terminal.

  

SIGCHLD

  A complete programming procedures, the child process to terminate, withdraw from, the kernel sends a SIGCHLD signal to the parent process, tell yourself the parent mission has been completed, the parent process will rehabilitate the received signal (the child receives the child process the exit status, the release of resources is not closed), while the kernel will carry out some remedial operations (such as cleaning up the entry process, close open files, etc.).

  Normally, the process will end after a short time in a zombie state (SIGCHLD signal sent to the parent process between reception of the signal and make treatment), but this time is very short, hardly ps or top command catch. Under special circumstances, the child dies, the parent process SIGCHLD signal is not received, then the process will be in a permanent state of zombies. Zombie undead, humans will be in trouble, zombie process consumes system resources, if many, would severely affect server performance. Although the kernel will regularly clean up their own following a variety of zombies, but zombie process has cover for its parent process (parent process SIGCHLD signal is not received, do not know the child process becomes a zombie process), the kernel is not seen zombie process, and send signals directly to the zombie is no effect, because the process is a zombie process has been terminated, not receiving a signal. How does it deal with zombies? Two ways:

  • Directly kill the parent process zombie process, the saying goes: the child does not teach, the father of. . . It would be cruel to the point.

  • Manually send SIGCHLD signal to the parent process zombie process. The parent did not know that their children become zombies, we manually tell it, and then it tells the kernel to deal with.

  

Manual transmission signal

  Use the kill command to manually send a signal to the specified process

[root@template ~]# man kill
SYNOPSIS
       kill [-s signal|-p] [-q sigval] [-a] [--] pid...
       kill -l [signal]
# 列出所有支持的信号
[root@template ~]# kill -l
# 示例
[root@template ~]# tailf .bashrc
# 另开一个窗口
[root@template ~]# ps -ef | grep [t]ailf
root      13549  13525  0 20:51 pts/0    00:00:00 tailf .bashrc
[root@template ~]# kill -KILL 13549 或者 kill -9


Reference material

  • Horse Jinlong blog: https: //www.cnblogs.com/f-ck-need-u/p/7058920.html#auto_id_14


This blog borrowed horse dragon big brother blog, and he summed up the part, in fact, that is to learn as it ...... plagiarism because some of the content in this article is a copy of (I will notify the author), I really want no more appropriate vocabulary. Ashamed! Ashamed sum ah!


Writing is not easy, please indicate the source, thank you ~~

Guess you like

Origin www.cnblogs.com/ccbloom/p/11297465.html