Reading Notes-apue 3-(8) Process Control

Source: Internet
Author: User
Process ID

Each process has a unique process ID. Several special processes:

  1. Process 0 is a kernel process, generally a scheduling process Swapper.
  2. Process 1 init is a user process (run/sbin/init with root permission) and is responsible for initialization.
  3. Several important functions: getpid (process ID)/getppid (parent process ID)/getuid (process has user ID)/geteuid (process valid user ID)/getgid (process has user group ID) /getegid (valid process user group ID ).

Fork/exec/Wait routine

Fork family functions are used to create sub-processes (detailed description of parent-child process relationships ), child processes often call the exec family function to run New Programs (fork + exec operations are called spawn hatching in some systems), while the wait family function is used to obtain the child Process Termination status.

The system function uses/bin/sh to run the command. The following is the simple version number implemented by fork/exec/Wait.

# Include <sys/Wait. h> # include <errno. h> # include <unistd. h> INT system (constchar * character string)/* version without signal handling */{pid_t PID; int status; If (character string = NULL) Return (1 ); /* always a command processor withunix */If (pid = fork () <0) {status =-1;} else if (pid = 0) {/* fork returns 0, indicating that */execl ("/bin/sh", "sh", "-c", struct string, (char *) is in the sub-process *) 0); _ exit (127);/* execl Error */} else { /* In the parent process, fork returns the child process PID */while (waitpid (PID, & status, 0) <0) {If (errno! = Eintr) {status =-1;/* error other than eintr fromwaitpid () */break ;}} return (Status );}

  1. ForkA function is returned twice in the parent process and itself. Because the parent process can fork multiple child processes, it is designed to return the child process PID in the parent process, when the sub-process returns 0, the sub-process can obtain its own PID and its parent process PID through getpid and getppid. A common application scenario is that in network programming, the parent process while loop listens to user requests. When a user request is received, fork sends a child process for processing. Note: in Linux, fork is called by clone system.
  2. WaipidThe function uses the number of bytes 0 to wait for the return of the specified sub-process. The wait function family containsWait(Wait for any sub-process to return )/Waitpid(Wait for the return of the specified sub-process and group, and set the blocking option through the third limit )/Waittid(Further expansion can be used to obtain signal information that causes Process Termination, etc )/Wait3(Resources used by the process can also be returned )/Wait4(Other wait function entry ).
  3. ExecThe role of a family function is to replace the current process context (text/data/Heap/stack) and run New Programs (no new processes will be created ).ExecFamily functionsExecl/execlp/execle/execv/execvp/execveThe main difference between functions is the number of percentages. In this example, L indicates the list form, V indicates the pointer array form, e indicates the environment variable, and P indicates that the number of percentages indicates the relative path, it will be searched in the path.

Parent and Child Processes

The sub-process and the parent process share only the read text segment. For the BSS segment, the pair, and stack, the modern operating system uses the cow (copy-on-write) technology, only when there is a change, to copy the corresponding Memory Page.

Parent-Child process relationship

A child process inherits a large number of attributes of the parent process, including real/valid user information, process group/session information, working folders, environment variables, and resource restrictions.

The most obvious difference between parent and child processes is that the TMS time statistics of sub-processes are cleared, and sub-processes do not inherit File locks, pending alarms and signals (as discussed in some chapters ).

The returned sequence of sub-processes and parent processes is uncertain. Assuming that the user program depends on the Operation Sequence of the Parent and Child processes, it must be processed by itself, for example, using signals to implement the wait notification mechanism.

  1. The kernel retains a small amount of information (PID, termination status, CPU time, etc.) for each terminated process, so that the parent process can obtain its termination status.
  2. If the child process ends before the parent process, and the parent process does not have wait, the child process will become a zombie process.
  3. Assume that the parent process ends first and the parent process of the child process changes to the INIT process (PID is 1). To avoid the occurrence of a zombie process, you can call fork twice, that is, call fork again in the sub-process and exit. In this way, the second fork process is taken over by the INIT process because its parent process exits.

File Sharing

The sub-process displays the file descriptor opened by the DUP parent process (the close-on-exec Mark of the shared file descriptor), including standard output, input, and error output.


The Parent and Child processes share the file tableentry, with the same location offset. Therefore, when the parent and child processes read and write the same file, pay attention to synchronization.

Set process user ID

As mentioned earlier, sub-processes inherit the UID and EUID (valid user ID) of the parent process, and can call setuid (setgid) to modify the process user (group ).

  1. If it is called by the root user, the UID, EUID, and backup EUID (saved set-user-ID) of the process will be changed at the same time ). After login, the login (root process) sets the user ID.
  2. Non-root users can only change the EUID, and only change it to the UID or backup EUID. Otherwise, an error occurs.
  3. If the self-process runs the exec method and the set-user-ID bit of the running program is set, the EUID is set to the master ID of the running program.
  4. Backup EUID copy EUID. Under normal circumstances, uid = EUID = backup EUID.
  5. The programming follows the "minimum permission" model. If the program requires a high permission, the setuid is called to escalate the permission. After the operation, the setuid is called to restore the permission.

Other process-related functions

  1. Process audit:AcctEnable process audit. The system records statistics of terminated processes, including the user ID, start time, and CPU time. The audit records of the Linux system are stored in/var/log/account/pacct. You need to use fread to read the Acct structure information.
  2. Process Scheduling: The process adjusts the nice value to set the execution priority (the more nice you are, the lower your priority is, and the worker does not split it ..), Related functions:Nice/getpriority/setpriority
  3. Process Time: Call clock_tTimes(Structtms *Buf) Function, where the return value is the clock time, And the TMS struct is filled with the following content:

struct tms {    clock_t tms_utime; /* user CPU time */    clock_t tms_stime; /* system CPU time */    clock_t tms_cutime; /* user CPU time, terminated children */    clock_t tms_cstime; /* system CPU time, terminated children */};

Note: The related time has been converted into seconds by the number of tick answers per second (_ SC _clk_tck), but it is counted from any time in the past, so its absolute value is meaningless. Generally, the time difference between the start and end times of the process is calculated.

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.