Lesson Five Process Management

Source: Internet
Author: User
Tags bit set terminates cpu usage

Unix_c_05.txt
================
Lesson Five Process Management
================
First, the basic concept
------------
1. Processes and Procedures
~~~~~~~~~~~~~
1) The process is the running program. A running program,
There may be multiple processes. The process performs a specific task in the operating system.
2) The program is stored on the disk,
A static entity that contains executable machine instructions and data.
A process or task is a computer program that is active.
2. Classification of processes
~~~~~~~~~~~~~
1) The process is generally divided into three categories: interactive process, batch process and daemon process.
2) daemons are always active, usually running in the background.
Daemons are typically activated automatically by the system at boot time by a script,
Or it can be started by Superuser root.
3. View the process
~~~~~~~~~~~
1) Simple Form
# PS
Displays the process information for the current user with control terminal in a shorthand manner.
2) BSD style common options
# PS Axu
A-all users have the process of controlling the terminal
X-includes a process with no control terminal
U-Display in an exhaustive manner
W-Display in a larger column width
3) SVR4 style common options
# PS-EFL
-E or-A-process for all users
-A-process of the current terminal
-u user name or user ID-process for a specific user
-G group name or group ID-process for a specific group
-F-Display in full format
-F-Display in more complete format
-L-Display by long format
1th page Unix_c_05.txt
4) Process Information list
User/uid: Process owner.
PID: Process ID.
%CPU/C: CPU usage.
%MEM: Memory utilization.
VSZ: Takes up virtual memory size (KB).
RSS: The physical memory size in kilobytes (KB).
TTY: Terminal device number, "?" Represents a non-control terminal, such as a background process.
STAT/S: Process state. The following values are desirable:
O-ready. Waiting to be dispatched.
R-run. There is no O status under Linux, and the ready state is also indicated by R.
S-wakes up to sleep. The system interrupts, gets the resources, receives the signal,
Can be woken up and transferred to a running state.
D-No waking sleep. Can only be awakened by the WAKE_UP system call.
T-Pause. Received the sigstop signal into the suspended state,
Receive the Sigcont signal into the running state.
W-Waits for memory paging (the 2.6 kernel is discarded later).
X-Death. Not visible.
Z-Zombies. has stopped running, but its parent process has not yet acquired its state.
<-high priority.
N-Low priority.
L-There is a paging that is locked into memory. Real-time process and custom IO.
S-session first process.
L-Multithreading process.
+-in the foreground process group.
Start/stime: Process start time.
Time: Process runtime.
Command/cmd: Process directives.
F: Process flag. Can be taken from the following values:
1-generated by fork but no exec.
4-Super User privileges.
PPID: Parent Process ID.
NI: Process Nice value, 20 to 19, can be modified by system call or command.
PRI: Process priority.
Static priority = Nice,60 to 99, the smaller the value the higher the priority.
The kernel is based on the static priority,
The actual (dynamic) priority is calculated based on the interaction of the process.
To reflect the rewards of IO-consuming processes,
2nd Page Unix_c_05.txt
and penalties for processor-consuming processes.
ADDR: The memory address of the kernel process. The normal process displays "-".
SZ: The number of virtual memory pages occupied.
Wchan: The kernel function or event that the process is waiting for.
PSR: The processor to which the process is bound.
4. Parent process, child process, orphan process, and zombie process
-------------------------------------
Kernel processes (0)
Init (1)
xinetd
in.telnetd <-User Login
Login
Bash
Vi
1) After the parent process starts the child process,
The child process runs concurrently with its parent process under the dispatch of the operating system.
2) The child process ends before the parent process,
The child process sends a SIGCHLD (17) signal to the parent process,
The parent process reclaims related resources for the child process.
3) The parent process ends before the child process, and the child process becomes the orphan process,
Being adopted by the INIT process at the same time, it becomes the child process of the INIT process.
4) The child process ends before the parent process,
But the parent process does not reclaim the associated resources for the child process.
The child process becomes a zombie process.
5. Process identifier (process ID)
~~~~~~~~~~~~~~~~~~~~~
1) Each process has a unique identifier represented by a nonnegative integer,
That is, the process id/pid.
2) The process ID is unique at any time, but can be reused,
When a process exits, its process ID can be used by other processes.
3) deferred reuse.
a.out-1000
a.out-1010
a.out-1020
...
Example: DELAY.C
Second, Getxxxid
------------
3rd page Unix_c_05.txt
#include <unistd.h>
Getpid-Get Process ID
Getppid-Gets the parent process ID
Getuid-Get the actual user ID
Geteuid-Get a valid user ID
Getgid-Get the actual group ID
Getegid-Get valid group ID
Example: ID.C
Log in as a different user and execute
$ a.out
Output
Process ID: ...
Parent Process ID: ...
Actual user id:1000-actual user ID takes the actual user ID of the parent process (shell)
Valid user id:1000-valid user ID takes the actual user ID
Actual group id:1000-Actual group ID takes the actual group ID of the parent process (shell)
Valid group id:1000-valid group ID fetch actual group ID
Perform
# ls-l A.out
Output
-rwxr-xr-x ...
^ ^
Add set User ID bit and set group ID bit for a.out file permissions
# chmod U+s a.out
# chmod G+s a.out
Perform
# ls-l A.out
Output
-rwsr-sr-x ...
^ ^
Log in as a different user and execute
$ a.out
Output
Process ID: ...
Parent Process ID: ...
Actual user id:1000-actual user ID takes the actual user ID of the parent process (shell)
Valid user id:0-the master ID of the valid user ID accessor file
Actual group id:1000-Actual group ID takes the actual group ID of the parent process (shell)
Valid group id:0-the group ID of the valid group ID to take the program file
The access rights of a process are determined by their valid user ID and valid group ID.
This method allows the process to obtain higher permissions than the logged-on user.
For example, through the passwd command to modify the login password.
Perform
Ls-l/etc/passwd
Output
-rw-r--r--. 1 root root 1648 Nov 9 14:05/etc/passwd
^
4th page Unix_c_05.txt
This file contains all the user's password information, only the root user can write,
But in fact any user can modify their login password,
That is, any user can write the file through the/USR/BIN/PASSWD program.
Perform
# ls-l/USR/BIN/PASSWD
Output
-rwsr-xr-x. 1 root root 28816 Feb 8 2011/usr/bin/passwd
^ ^
The program has a user ID bit set and its owner is root.
So log in to the system as any user, execute the process initiated by the passwd command,
Its valid user ID is root and has write access to the/etc/passwd file.
Third, fork
--------
#include <unistd.h>
pid_t fork (void);
1. Create a child process, fail back-1.
2. Call once and return two times.
Returns the PID and 0 of the child process, respectively, in the parent-child process.
Using the different return values,
You can write different processing branches for parent-child processes, respectively.
Example: FORK.C
3. The child process is a copy of the parent process.
The child process obtains a copy of the parent process data segment and the stack segment (including the I/O stream buffer),
But the child process shares the code snippet of the parent process.
Example: MEM.C, OS.C, IS.C
4. After the function call, the parent and child processes continue to run
Its sequencing is uncertain.
Some implementations can guarantee that the child process is dispatched first.
5. After the function call,
The file descriptor list (process level) of the parent process is also copied to the child process.
Both share the same file table (kernel level).
Example: FTAB.C
6. The number of processes owned by the total number of processes or the actual user ID,
The function will fail if the system limit is exceeded.
7. A process if you want to create your own copy and execute the same code,
Or you want to run concurrently with another program, you can use this function.
8. Orphan process with zombie process.
Example: ORPHAN.C, zombie.c
Note: The code before fork is only executed by the parent process,
5th page Unix_c_05.txt
The code that follows the fork has the opportunity to execute the parent-child process.
into different branches under the control of the Code logic.
Iv. vfork
---------
#include <unistd.h>
pid_t vfork (void);
The function is basically the same as fork, the difference between the two:
1. Calling vfork when creating a child process does not replicate the address space of the parent process.
The child process can pass the EXEC function family,
Start another process directly to replace itself,
This improves the efficiency of process creation.
2. After the vfork call, the child process is dispatched first.
V. Normal exit of the process
------------------
1. Return from the main function.
int main (...) {
...
return x;
}
Equivalent to:
int main (...) {
...
Exit (x);
}
2. Call the Exit function of the standard C language.
#include <stdlib.h>
void exit (int status);
1) Call process exits,
Its parent process calls the Wait/waitpid function to return the low 8 bits of status.
2) before the process exits,
Call all functions that were previously registered through the Atexit/on_exit function,
Flush and close all standard I/O streams that are still open
Delete all files created through the Tmpfile function.
#include <stdlib.h>
int atexit (void (*function) (void));
Functions-function pointers,
A function that needs to be called before the process exits.
6th page Unix_c_05.txt
The function has neither a return value nor a parameter.
Successful return 0, failure returns nonzero.
int on_exit (void (*function) (int, void*), void* Arg);
Functions-function pointers,
A function that needs to be called before the process exits.
The function does not have a return value but has two parameters:
The first parameter is from the status parameter of the Exit function,
The second argument is from the arg parameter of the On_exit function.
Arg-arbitrary Pointer,
will be passed as the second argument to the function that functions point to.
Successful return 0, failure returns nonzero.
3) Use Exit_success/exit_failure Macro constants
(possibly 0/1) as a parameter, call the exit () function to indicate success/failure,
Improve platform compatibility.
4) The function does not return.
5) The implementation of this function calls the _exit/_exit function.
3. Call the _exit/_exit function.
#include <unistd.h>
void _exit (int status);
1) Call process exits,
Its parent process calls the Wait/waitpid function to return the low 8 bits of status.
2) before the process exits,
First close all file descriptors that are still open,
The adoption of all its sub-processes to the INIT process (the PID 1 process)
Delivers a sigchild signal to the parent process.
3) The function does not return.
4) The function has a fully equivalent standard C version:
#include <stdlib.h>
void _exit (int status);
4. The last thread of the process executed the return statement.
5. The last thread of the process calls the Pthread_exit function.
Example: exit.c
Vi. abnormal termination of the process
------------------
7th page Unix_c_05.txt
1. Call the Abort function to generate a SIGABRT signal.
2. The process receives some signals.
3. The last thread responds to a "cancel" request.
Seven, Wait/waitpid
----------------
Waits for the child process to terminate and get its terminating state.
#include <sys/types.h>
#include <sys/wait.h>
pid_t Wait (int* status);
pid_t waitpid (pid_t pid, int* status, int options);
Successfully returns the PID of the terminating subprocess, which fails back to 1.
1. When a process is normal or abnormally terminated,
The kernel sends a SIGCHLD signal to its parent process.
The parent process can ignore the signal,
or provide a signal processing function for the signal, which is ignored by default.
2. The parent process calls the wait function:
1) block If all child processes are running.
2) If a child process has been terminated,
Returns the PID and termination state of the child process (via the status parameter).
3) If there is no need to wait for the child process, the return fails, errno is echild.
3. Before any of the child processes are terminated, the wait function can only block the calling process.
And the Waitpid function can have more options.
4. If there is a child process before the wait function is called,
has been terminated and is in zombie state, the wait function returns immediately,
And gets the terminating state of the child process.
5. The terminating state of the child process is returned to the caller by the output parameter status,
If you do not care about the terminating state, you can leave this parameter blank.
6. The terminating state of a child process can be
View the parameter macros defined in Sys/wait.h:
Wifexited (): Whether the child process terminates normally,
Yes, by Wexitstatus () macro,
Gets the child process call exit/_exit/_exit function,
The lower 8 bits of the passed parameter.
Therefore, the parameters passed to the Exit/_exit/_exit function should not be more than 255.
Wifsignaled (): Whether the child process terminates abnormally,
Yes, the Wtermsig () macro gets the signal to terminate the child process.
8th Page Unix_c_05.txt
Wifstopped (): Whether the child process is paused,
Yes, the signal to pause the subprocess is obtained through the WSTOPSIG () macro.
Wifcontinued (): Whether the child process continues to run after a pause
Example: Wait.c, loop.c
7. If there are multiple child processes at the same time, and you need to wait for a specific subprocess,
You can use the Waitpid function with its PID parameters:
-1-Waits for any child process, at which time the wait function is equivalent.
> 0-waits for the specific child process identified by this parameter.
0-Wait for its group ID to be equal to any child process that invokes the process group ID.
That is, any child process that waits for the same process group as the calling process.
<-1-Waits for any child process whose group ID is equal to the absolute value of the parameter.
That is, waiting for any child process that is subordinate to a particular process group.
Example: WAITPID.C
8. The options parameter of the Waitpid function is preferable to 0 (omitted) or a bit of the following value or:
Wnohang-Non-blocking mode,
Returns 0 if no child process state is available.
wuntraced-If job control is supported and the child process is in a paused state,
The status is returned.
wcontinued-If job control is supported and the child process is paused and continues,
The status is returned.
Example: NOHANG.C
VIII. exec
--------
1. The EXEC function will completely replace the calling process with the new process.
and starts executing from the main function.
2. The EXEC function does not create a child process, and the new process takes the PID of the calling process.
3. The new process created by the EXEC function,
Completely replaces the code snippet, data segment, and stack segment of the calling process.
4. If the EXEC function succeeds, it will not be returned, otherwise 1.
5. The EXEC function consists of six forms:
#include <unistd.h>
int Execl (
Const char* Path,
Const char* ARG, ...
);
9th Page Unix_c_05.txt
int Execv (
Const char* Path,
char* Const argv[]
);
int Execle (
Const char* Path,
Const char* ARG,
...,
char* Const envp[]
);
int Execve (
Const char* Path,
char* Const argv[],
char* Const envp[]
);
int EXECLP (
Const char* File,
Const char* ARG,
...
);
int EXECVP (const char* file,
char* Const argv[]
);
L: The command parameters of the new program are passed in as a separate string pointer
(const char* ARG, ...), the parameter table ends with a null pointer.
V: the command parameters of the new program are passed in as a string pointer array
(char* const argv[]), the array ends with a null pointer.
E: The environment variables of the new program are passed in as a string pointer array
(char* const envp[]), the array ends with a null pointer,
No e is copied from the Environ variable of the calling process.
P: If the first parameter does not contain "/", it is treated as a file name,
Search for the file according to the PATH environment variable.
Example: ARGENV.C, EXEC.C
IX. System
----------
#include <stdlib.h>
int system (const char* command);
1. Standard C functions. Execute command,
Successfully returns the terminating state of the command corresponding to the process, and the failure returns-1.
2. If command is null, returning nonzero indicates that the shell is available,
Returning 0 indicates that the shell is not available.
10th page Unix_c_05.txt
3. The implementation of the function,
Functions such as fork, exec, and waitpid are called.
Its return value:
1) Returns-1 if there is an error calling the fork or Waitpid function.
2) If there is an error calling the EXEC function, exit (127) is executed in the child process.
3) If all succeeds, returns the terminating status of the command corresponding process
(obtained by the status output parameter of the Waitpid).
4. The advantage of using the system function without fork+exec is that
The system function does the necessary processing for various errors and signals.
Example: SYSTEM.C, fexe.c
11th page

Lesson Five Process Management

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.