Process status and management of Linux

Source: Internet
Author: User
Tags sleep function terminates

Process Status:

1) Overview of the status of the process:

1.1) Running (R), running or going to run
1.2) interruptible (S), blocked while waiting for an event, may be activated by a signal
1.3) uninterruptible (D), blocked while waiting for an event, will not be activated by the signal
1.4) Stopped (T), terminated as a result of task control or external tracing, for example: Strace
1.5) Zombie (Z), zombie, but its parent process has not yet called the wait function.
1.6) Deal (X), this is never visible

The definitions in the kernel source code are as follows:


=====================================================
/usr/src/linux/fs/proc/array.c


Static const char *task_state_array[] = {
        R (running),          /*  0 */
        "S ( Sleeping) ",        /*  1 */
         "D (disk Sleep)",      /*  2 */
         "T (Stopped)",         /*  4 */
         "T (Tracing Stop)",    /*  8 */
         "Z (Zombie)",           */* */
         "X (dead)"               /* + */
};
=====================================================

It is defined in the help of the PS command as follows:

PROCESS State CODES
Here is the different values that the S, stat and state output specifiers (header "Stat" or "s") would display to
Describe the state of a process.
D uninterruptible sleep (usually IO)
R Running or runnable (on run queue)
S interruptible sleep (waiting for a event to complete)
T Stopped, either by a job control signal or because it is being traced.
W paging (not valid since the 2.6.xx kernel)
X dead (should never be seen)
Z Defunct ("zombie") process, terminated but not reaped by its parent.

       for BSD formats and when the STAT keyword are used, additional characters may di Splayed:
       <    high-priority (not friendly to other users)
       n    low-priority (Nice-to-other users)
        l    has pages locked to memory (for real-time and custom IO)
&NBSP;&NBSP;&NBSP;&N bsp;   s    is a session leader
       l    is multi-threaded (using Clone_thread, like NPTL pthreads do)
       +     is in the foreground process group
======================================================

  An interesting explanation of the D and Z:
 
    There is a class of rubbish that is not so easy to clean, that is, our common state is D (uninterruptible sleep), and the state is Z (Zombie) of the garbage process. These garbage processes are either begging or not, like a disgruntled woman waiting for resources (D), or stiff and immortal, waiting for the cross-over (Z) like ghost, they are stuck in the CPU run_queue, the Load Average is old high, Have not seen my previous blog of the International friends also thought here resentment again what big thing. What to do? Shoot! kill-9! Let's see if you go. But the two kinds of garbage process is invulnerable, no matter what kind of marksmanship can not kill them. Helpless, had to reboot, like to destroy the avian flu as indiscriminately all culling!
 
    resentment D, often because I/O resources are not met, and trigger wait, in the kernel source fs/proc/array.c, its text is defined as "D (disk Sleep)",/* 2 * * ( So D is originally the letter of disk, which corresponds to the "#define Task_uninterruptible 2" in Include/linux/sched.h. For example, when the NFS server is closed, if the relevant directory is not umount in advance, the NFS client executes DF to hang up the entire login session, pressing CTRL + C, CTRL + Z is useless. Disconnect and then log in, perform PS AXF see just the DF process status bit has become D, kill-9 can not kill. The correct way to do this is to restore the NFS server immediately, again to provide services, just suspended DF process found its hard to wait for the resources, then complete the task, automatic extinction. If the NFS server is unable to recover the service, the relevant NFS mount entry in/etc/mtab should be removed before reboot, so that the system restart process hangs if the wait resource is not repeated when the reboot process calls Netfs stop.

Ghost Z why Kill, because it is dead, otherwise how to call Zombie (zombie)? Ghost does not disperse, nature is the reason that the knot is not solved. In Unix/linux, each process has a parent process, howl PID (Process ID), and, accordingly, the parent process number is called PPID (parent PID). When the process dies, it automatically closes the open file, discards the system resources that have occupied memory, swap space, and so on, and returns an exit status value to its parent process, reporting the death. If the program has a bug, it will be a problem in this last step. My son said I was dead, but I did not hear, not in time to collect the coffin departures, the son became a zombie. In Unix/linux the means of eliminating zombies is more brutal, perform PS AXJF find the zombie process of the parent process number (PPID, the first column), first kill its father, and then by the process of the Emperor Init (its PID is 1,ppid 0) to clean up the father and son zombies, cross the Wraith, to the birth of bliss. Note that the child process becomes a zombie just an eyesore, not in the way, if the zombie parent process is currently a priority, you must not be rushed to kill it.


2) Analyze non-disruptive sleep processes:


2.1) Reproduce:

Terminal 1)

VI test.c
#include <unistd.h>

void Main () {
if (!vfork ()) sleep (100);
}
GCC Test.c-o Test

./test

Terminal 2)
PS Aux|grep Test
Root 19884 0.0 0.0 3640, pts/0 d+ 16:38 0:00./test
Root 19885 0.0 0.0 3640, pts/0 s+ 16:38 0:00./test


2.2) Analysis:
System entry This non-disruptive is rare, even if the occurrence is also a transient state, causing the occurrence of this state is generally a driver.
For example, a driver may be waiting on a special device for a response to be detected, but also to ensure that it is not interrupted in the Interruptible Sleep State (S). So the driver switches the process to a non-interruptible sleep state until the hardware has returned to a known state.


You can observe non-disruptive sleep states by accessing a slow device, such as a device like CDROM
For example:
DD If=/dev/cdrom F=/dev/null &


The process is very dangerous in a non-interruptible state, you can't kill it with Kill-9.
For example:
A problematic driver accesses a problematic device, the device does not respond to the driver, the driver never responds, and waits for the response forever.

3) Analyze the status of the process being tracked or stopped (T)


3.1) Reproduce the status when being tracked:

Terminal 1)
Strace Top

Terminal 2)
PS Auxf|grep Top
Root 980 9.4 0.0 1716 608 pts/0 S 00:31 0:12 | \_ Strace Top
Root 981 3.7 0.1 10084 7076 pts/0 T 00:31 0:05 | \_ Top

The top process is the state of t when tracking top execution with Strace


3.2) Reproduce the status of the stopped process:

There are three ways to stop a process:
3.2.1) Send SIGTSTP message to stop the process.
The-SIGTSTP signal is equivalent to CTRL + Z's key combination to terminate the process that is running in the foreground.

Terminal 1)
vi/etc/passwd

Terminal 2)
KILL-SIGTSTP 12029

To view the status of a process:
PS AUXF

Root 10297 0.0 1.0 5124 2696 pts/0 ss+ Dec16 0:00 \_-bash
Root 12029 0.0 0.8 5348 2200 pts/0 T 05:15 0:00 | \_ VI test.c


Terminal 1)
View jobs put in the background
Jobs
[1]+ Stopped VI test.c

Switch jobs to the foreground with FG
Fg


3.2.2) process self-terminates, standard input causes process to stop

A terminal with the regular background and foreground process management process, a terminal has and only one foreground process, only this process can accept the keyboard input, any other process started in the terminal is considered a background process, but when the background process attempts to read data from the standard input, The terminal will send a sigttin terminal to it because there is only one input device keyboard, which can only be used for foreground processes.
The front and back process concepts here are limited to the scope of the terminal.

Sigttin when a background job wants to read data from a user terminal, all processes in that job receive a sigttin signal. By default, these processes stop executing.


Terminal 1)

Try to run the Read command in the background because the background process cannot get the standard input from the terminal, so the process will receive a signal sigttin to get the process into a stopped state.
Read X &
[1] 12057

[1]+ Stopped Read X

Terminal 2)
Jobs
[1]+ Stopped Read X
View process, 12057 This PID is read x& now see is-bash, its state is already t
PS aux
Root 12057 0.0 0.5 5124 1476 pts/0 T 05:26 0:00-bash

Wake up with Sigcont.
Kill-sigcont 12057

Terminal 1)
After entering enter, 12057 of the process will still go to the stop state, that is, blocking, only after it is placed in the foreground, it can complete the input.
Fg
Read X
Hello

3.2.3) process self-terminates, standard output causes process to stop

The terminal has a tostop (terminal output termination) setting, which is turned off by default in most systems.
When the status is off, the background process can write to the terminal at any time, and if it is on, the background process will be terminated when it writes data to the standard output.


Open Tostop
Stty tostop

Write data to standard output, stopped
echo Hello World &
[1] 12125

[1]+ Stopped echo Hello World

Jobs
[1]+ Stopped echo Hello World

Close Tostop
Stty-tostop

Jobs
[1]+ Stopped echo Hello World

Write data to standard output is back to normal.
Fg
echo Hello World
Hello World

4) interrupted sleep state and operating state of the analysis process



Write a small program to test the transitions after the sleep state and the running state:
=====================================================
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <stdlib.h>

void
Run_status (void)
{
Double pi = m_pi;
Double pisqrt;
Long I;

for (i=0; i<100000000; ++i) {
pisqrt = sqrt (pi);
}
}

Int
Main (void)
{
Run_status ();
Sleep (10);
Run_status ();

Exit (exit_success);
}
======================================================
After compiling the link:
Gcc-wall-o pisqrt A.C-LM


Terminal 1)
Monitor the PISQRT process
Watch-n 1 "PS aux|grep pisqrt|grep-v Ps|awk ' {print $} ' |sort-k 8 '


Terminal 2)
Strace./pisqrt
appears as follows:
Read (3, "\177elf\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\200x\1" ..., (+) =
Fstat64 (3, {st_mode=s_ifreg|0755, st_size=1572440, ...}) = 0
Old_mmap (NULL, 1279916, prot_read| Prot_exec, Map_private, 3, 0) = 0x49e000
Old_mmap (0x5d1000, 12288, prot_read| Prot_write, map_private| Map_fixed, 3, 0x132000) = 0x5d1000
Old_mmap (0x5d4000, 10156, prot_read| Prot_write, map_private| map_fixed| Map_anonymous,-1, 0) = 0x5d4000
Close (3)                                   = 0
Set_thread_area ({entry_number:-1-6, Base_addr:0xb75e3a60, limit:1048575, Seg_32bit:1, contents:0, read_exec_only:0, Limit_in_pages:1, seg_not_present:0, useable:1}) = 0
Munmap (0xb75e4000, 75579)                 = 0

At this point switch to Terminal 1 to see the PISQRT process state, at this time the R state:
Root 3792 99.9 0.0 1516 268 pts/2 R 02:40 0:01./pisqrt
Root 3801 0.0 0.0 3700 672 pts/1 S 02:40 0:00 grep pisqrt
Root 3791 1.0 0.0 1728 564 pts/2 S 02:40 0:00 strace./pisqr

After the PISQRT process enters the S state, the Sleep (10) function is executed, and after 10 seconds Pisqrt enters the R state again. Final Exit.

Analysis:
Pisqrt consumes CPU time and the state is R, and after the sleep function is called S, most of the system's process states are s, such as Apache and Oracle,
The S state does not necessarily call the sleep function, because IO also causes the process to sleep.
While we can start multiple pisqrt programs, there will be multiple r states in the system. That is, there is no direct correlation between the number of CPUs and the R process.


5) The dead state of the analysis process (Z)

When a process exits, it does not completely disappear, but waits until its parent process issues a wait system call to completely disappear unless the parent process issues a wait system call to terminate the process.
Otherwise, the process will remain in the so-called zombie State, waiting for its parent process to terminate it. If the parent process terminates the run without revoking the child process, those processes will be adopted by the process init.
The INIT process periodically calls wait to adopt these processes that have not been undone.

Make a zombie program first, as follows:
=============================
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

Int
Main () {
if (!fork ()) {
printf ("Child pid=%d\n", Getpid ());
Exit (5);
}
Sleep (20);
printf ("Parent pid=%d\n", Getpid ());
Exit (exit_success);
}
===========================================
Compile
Gcc-wall Defunct.c-o Defunct

Terminal 1:
Watch-n 1 "PS auxf|grep defunct|grep-v ps|grep-v Grep|awk ' {print $} ' |sort-k 8"


Terminal 2:
Execution./defunct

View Terminal 1:
Root 7280 0.0 0.0 1380 PTS/2 S 03:05 0:00 | \_./defunct
Root 7281 0.0 0.0 0 0 pts/2 Z 03:05 0:00 | \_ [defunct <defunct>]

See Terminal 2 after 20 seconds:
Child pid=7281
Parent pid=7280

Description of the signal set:/usr/include/bits/signum.h

#define SIGCLD SIGCHLD/* Same as SIGCHLD (System V). */
#define SIGCHLD/* Child status have changed (POSIX). */

The SIGCHLD signal can be recovered by adding the wait function on the basis of the above program

The modified program is as follows:
=================================
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

Int
Main () {
int status,i;
if (!fork ()) {
printf ("Child pid=%d\n", Getpid ());
Exit (5);
}
Wait (&status);
i = wexitstatus (status);
Sleep (20);
printf ("Parent Pid=%d,child process exit/status=%d\n", getpid (), i);
Exit (exit_success);
}
==========================================


6) Final process X (dead)
It means the dead process.

Last 4 kinds of additional states ....
W Status: Memory not residing
< status: Nice less than 0
N Status: Nice greater than 0
L Status: Locked page

This section is described in the PS source code (OUTPUT.C):
===================================
static int
Pr_stat (void)
{
int end = 0;
outbuf[end++] = pp->state;
if (Pp->rss = = 0 && pp->state! = ' Z ')
outbuf[end++] = ' W ';
if (Pp->nice < 0)
outbuf[end++] = ' < ';
if (Pp->nice > 0)
outbuf[end++] = ' N ';
if (Pp->vm_lock)
outbuf[end++] = ' L ';
Outbuf[end] = ' + ';
return end;
}
=====================================

Process Management:

FG, BG, Jobs, &, CTRL + Z command

First, &
At the end of a command, you can put this command in the background to perform, such as SH start.sh &


Two, CTRL + Z
A command that is executing in the foreground can be placed in the background and is paused for execution.


Iii. jobs: See how many are currently running in the background

The JOBS-L option shows the Pid,jobs status of all tasks can be running, stopped, Terminated, but if the task is terminated (kill)

FG: The command in the background is transferred to the foreground to run
If there are multiple commands in the background, you can use FG%jobnumber to bring up the selected command,%jobnumber is the ordinal of the command being executed in the background through the jobs command, not the PID


V. BG: a command that pauses in the background changes to continue execution ( background execution )
If there are multiple commands in the background, you can use BG%jobnumber to bring up the selected command,%jobnumber is the ordinal (not PID) of the command being executed in the background through the jobs command.
Move the task to the background run: Ctrl + Z, then BG, so that the process is moved to the background and the terminal can continue to accept commands.


Current task
If there are 2 task numbers in the background, [1],[2]; If the first background task executes successfully and the second background task is still in progress, the current task will automatically become a background task for the background task number "[2]". So it can be concluded that the current task is subject to change. When the user enters commands such as FG, BG, and stop, the current task is changed if no quotation marks are added

Termination of the process
Termination of the background process:
Method One:
View the job number (assuming num) through the jobs command, and then execute the kill%num


Method Two:
Use the PS command to view the job's process number (PID, assuming PID), and then execute the kill PID


Termination of the foreground process:
CTRL + C

Other effects of Kill
In addition to terminating the process, kill can also send other signals to the process, using kill-l to see the signals that kill supports.
Sigterm is the signal that kill sends without parameters, meaning that the process terminates, but execution depends on whether the process supports it. If the process has not been terminated, you can use the Kill-sigkill PID, which is the kernel to terminate the process and the process cannot listen for this signal.

Hang of background process:
In Redhat, the Stop command does not exist, and the process can be suspended by executing the command kill-stop PID;

When you want to re-execute a task that is currently suspended, you can change the status of the suspended job from stopped to running by using BG%num, which is still performed in the background, and execute the command FG%num when you need to do it in the foreground instead.

Foreground process hangs:
CTRL + Z

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.