"Linux" Process waiting & program replacement __linux

Source: Internet
Author: User
Tags function prototype stdin terminates

A process closes all file descriptors at the end, releasing memory allocated in user space, but its PCB remains.

The kernel holds some information in it: if it's a normal termination, save the exit state and, if it exits unexpectedly, save the information that caused the process to terminate. The process's parent process can call wait or waitpid to get the information, and then completely erase the process. We know that the exit status of a process can be in the shell with special variable $? View, because the shell is its parent process, and when it terminates, the shell invokes wait or waitpid to get its exit state and completely erase the process.

When a process is normal or abnormally terminated, the kernel sends a SIGCHLD signal to its parent process. Because a child process termination is an asynchronous event, the occurrence of this signal is also an asynchronous notification that the kernel sends to the parent process. The parent process can choose to ignore the signal or provide a function that is invoked when the signal occurs. The system default action for this signal is to ignore it.

The file descriptor, wait, or waitpid mentioned in the above description are described below

1. File descriptor

Three standard output streams: Stdin,stdout and stderr

#include <stdio.h>

extern file* stdin; extern file* stdout; Externa file* stderr;

File* This approach is provided by the C language (standard library), and any program running in the system defaults to the 3 standard input/output streams associated with the program, namely, the keyboard, the monitor, and the monitor.

1 file identifier: 0 for standard input, 1 for standard output, 2 for standard error.

The following procedure explains


2 The file descriptor is a series of small integers starting from 0, and the program runs to form a process that finds files through the process and opens 3 files 0,1,2 by default. After the file is opened, the file descriptor is incremented starting from 3. As shown in the figure

Once a file descriptor is closed, the subsequent file description Fuxian the closing file descriptor, and then increments from 3. Close 0, or turn off standard input, as shown in figure:

3 system call on the lower level of the library function, the library function calls the system function.

2. Wait () or waitpid () function

Header file:

#include <sys/types.h>

#include <sys/wait.h>

Wait function:

1) pid_t Wait (int *status);

Return value: Successfully returned by wait process PID, failed return-1

Parameters: output parameter, get process exit state, no care can be set to NULL

If a process calls wait because it receives SIGCHLD, you can expect wait to return immediately, but if you call wait at any time, the process may block.

Before a child process terminates, wait causes its caller to block, and Waitpid has an option to make the caller not clog. If status is not a null pointer, the termination status of the terminating process is stored in the cell that it refers to. If you do not care about the termination state, you can set the parameter to a null pointer (Waitpid also applies).


2) pid_t waitpid (int *status);

return value:

A, when the normal return waitpid returns the process ID of the collected child process

b, if the option Wnohang is set, and Waipid in the call discovers that no child processes have been evicted to collect, return 0

c, if the caller fails, return-1, which is errno will be set to the appropriate value to indicate the error

D, when the PID indicates that the child process does not exist, or that the process exists, but is not a child of the calling process, Waitpid will return with an error, when errno is set to Echild

Parameters:

A, PID (process ID)

Pid=-1, waiting for any child process to be equivalent to wait.

PID >0; a subprocess that waits for its process ID to be equal to the PID.

PID = = 0; waits for the any subprocess whose group ID is equal to the process group ID.

PID <-1; any subprocess that waits for its group ID to be equal to the PID absolute value.

b, status (int type)

Status High 8-bit (wifexited (status)): True if the state returned for normal termination of the child process. (To see if the process is quitting normally)
Status low 8 bit (Wexitstatus (status)): If wifexited Non-zero, extract the subprocess exit code. (View exit code for process)

C, Options (Waiting mode)

The options are 0: Blocking waits, which is called blocking waiting.

The options are Wnohang: If the PID-specified subprocess does not end, the Waitpid () function returns 0 (no errors, no read success) and does not wait. If the end is normal, the ID of the child process is returned.

  1/*************************************************************************    2     > File name:wait.c    3     > author:ma6174    4     > mail:ma6174@163.com     5     > Created time:2016 year July 24 Sunday 19:57 23 sec     6  ************************** /    7     8 #include <stdio.h>    9 #
include<sys/types.h>   10 #include <sys/wait.h>   11 #include <stdlib.h>   12        13 int main ()    14 {   15     pid_t id = fork ();  & nbsp;16     if (ID < 0) {   17         printf ("fork failure\n");   18 & nbsp  }   19     ELSE if (id = 0) {   20         printf ("Child, pid:%d\n ", Getpid ());   21 &nbsP       Sleep (3);   22        //while (1);//will be waiting for child process to end   &NBSP;23   & nbsp     printf ("Child deading...\n");   24         exit (0);   25   &nbs P    //EXIT (123)//child process exit code   &NBSP;26        //exit (257);//Abnormal exit, overflow   &NBSP;27 & nbsp  }   28     else{   29         printf ("father,pid:%d\n", Getpid ()) ;   30        //pid_t ret = wait (NULL);/do not care about process exit status    31       &NBS P int status = 0;   32        //pid_t ret = waitpid (ID, &status,0);//0 indicates that the default is to wait in blocking mode &nbs
P  33         while (1) {   34             pid_t ret = WAITPI D (ID, Null,wnohang);   35             printf ("Father wait return...\n");  &NB Sp;36             sleep (1);   37             if (ret = 0 {//Process not closed    38                 printf ("Child is Running,please wait\n") ;   39            }//wait for success or failure to exit cycle    40         &NBS P   else if (ret = ID) {//wait child success   41                 Print F ("Wait success\n");   42                 break;   43   & nbsp            //printf ("code is done?") %d\n ", status&0xff)//See if the process is normal exit    44                //printf (" Exit code? %d\n ", (status>>8) &0xff)//View exit code    45            }else{                    printf ("WaiT failed\n ");   47                 break;   48     & nbsp      }   49             sleep (2);/hibernate 2 seconds, will not wait for    50 &nbs P      }   51    }   52    53}<span style= "color: #cc0000;" > </span>

The results of the operation are as follows:

3 Check the termination status returned by wait and Waitpid:

A, the use of bitwise-and, get static the first 8 digits and the latter 8 bits

b, using the macros in the system

wifexited (status): True if the state returned for normal termination of the child process.

Wexitstatus (status): If wifexited Non-zero, returns the subprocess exit code, the extraction process exits the return value, if the child process exit (7), Wexitstatus (status will return 7. Note that if the process does not exit normally, that is, wifexited returns 0, the value is meaningless.

Description: Status is not simply a cosmetic variable, the parent process and the child process all the state interaction between the two to be represented by this int, so that a number of bit bits of int have a special meaning, then this "int" How to encode is more important, and the same IP address, It is more compact, or rather crowded.

Status indicates whether the child process is exited normally or is terminated abnormally (a process can also be signaled by another process), as well as the return value at the end of the normal, or how much information is being terminated by which signal or process exit code, the information is placed in different bits of integers, So it's cumbersome to read in a regular way, so developers have designed a special set of macros (macro) to do the job.

4) The role of Wait and waitpid:

A, wait for the purpose: child process read to the child process exit a state information

b, let the system release the child processes occupy zombie state resources

C, the runtime does not guarantee the parent-child process who first run, to ensure that the child process to exit first, waiting for the parent-child process to exit synchronization (that is, exit to produce a certain order)

5 Waitpid provides functions not provided by wait:

A, waitpid can wait for a specific process

B, Waitpid provides a non-blocking version of wait

C, waitpid support job control

3. Process Program Replacement

After the child process is created with fork, it executes the same program as the parent process (but it is possible to execute different branch of code), and the child processes often invoke an EXEC function to execute another program. When a process invokes an EXEC function, the user-space code and data for the process are completely replaced by the new program, starting with the startup routine of the newly-executed program. Calling exec does not create a new process, so the ID of the process does not change before and after calling exec.

1 In fact there are 6 kinds of functions that begin with exec, collectively called the EXEC function:

#incldue <unistd.h>

int execl (const char* path,const char* arg,....);

int EXECLP (const char* file,const char* arg,....);

int execle (const char* path,const char* arg,..., char* const emp[]);

int execv (const char* path,char* const argv[));

int EXECP (const char* file,char* const argv[));

int Execve (const char* path,char* const argv[],char* Const emp[]);

These functions, if the call succeeds, loads the new program to start execution from the startup code and no longer returns.

Returns 1 if the call fails, so the EXEC function has only the wrong return value and no successful return value.

2 The rules of these functions:

The EXEC function without the letter P (representing path) must be the relative or absolute path of the program, such as "/bin/ls" or "./a.out", not "ls" or "a.out". For a function with the letter P: If the argument contains/, it is treated as a path name. Otherwise, as a program name without a path, search for the program in the directory list of the PATH environment variable.
The EXEC function with the letter L (representing the list) requires that each command-line argument for the new program be passed to it as a parameter, and the number of command-line arguments is variable, so there is a function prototype with ...,... The last variable parameter in is supposed to be null, which acts as a Sentinel.
A function with the letter V (Vector) should first construct an array of pointers to each parameter, and then pass the first address of the array as an argument, and the last pointer in the array should also be null, just like the argv parameter of the main function or the environment variable table.
For the EXEC function ending with e (Environment), a new environment variable table can be passed to it, and the other exec functions still use the current environment variable table to execute the new program.


The above processes are replaced with program execution as follows:



Open (), close (), write (), and read () functions under Linux

1. Open () function
Feature Description: For opening or creating files, you can specify various parameters such as the properties of the file and the permissions of the user when you open or create the file.
Required headers: #include <sys/types.h&gt, #include <sys/stat.h>, #include <fcntl.h>
Function prototypes: int open (const char *pathname,int flags,int perms)
Parameters:
Pathname: Name of the file being opened (may include pathname such as "DEV/TTYS0")
Flags: File open mode,
O_rdonly: Open File as read-only
O_wronly: Open File as Write-only
O_RDWR: Open File as read-write
O_creat: If the file does not exist, create a new file and set permissions for it with the third parameter
O_EXCL: If the file exists when using O_creat, an error message is returned. This parameter can test whether a file exists. Open is an atomic operation at this time, preventing multiple processes from creating the same file at the same time
O_noctty: When using this parameter, if the file is a terminal, then the terminal will not become the control terminal of the process that calls open ()
O_trunc: If the file already exists, it will delete all the original data in the file and set the file size to 0
O_append: Opens the file as an addition, and when the file is opened, the file pointer points to the end of the file, and the data that is being written is added to the end of the file
O_nonblock: If pathname refers to a FIFO, a block special file, or a character special file, this option sets the non-blocking for this file's open operation and subsequent I/O operations.
O_sync: Make each write wait until the physical I/O operation completes.
O_rsync:read waits for all writes written to the same area to complete before
In the open () function, the Falgs parameter can be passed through the "|" Composition, but the first 3 standard constants (O_rdonly,o_wronly, and O_RDWR) cannot be combined.
Perms: Access to the opened file can be represented in two ways, and can be defined in a set of macros: S_i (r/w/x) (Usr/grp/oth), where r/w/x represents read and write execution rights,
Usr/grp/oth represents the owner/file-owning group/Other user of the file, such as s_iruur| s_iwuur| S_ixuur, (-rex------), can also be used octal 800 to indicate the same permissions
return value:
Success: Return file descriptor
Failure: Return-1

2. Close () function
Feature Description: Used to close a file that was opened
Required header file: #include <unistd.h>
Function prototype: int close (int fd)
Parameters: FD File descriptor
function return value: 0 successful,-1 error

3. Read () function
Feature Description: Reads data from a file.
Required header file: #include <unistd.h>
Function prototype: ssize_t read (int fd, void *buf, size_t count);
Parameters:
FD: The file descriptor that will read the data.
BUF: A buffer in which the data read is placed in this buffer.
Count: Indicates how many characters should be read when a read operation is invoked.
Return value: Returns the number of bytes read; 0 (read EOF);-1 (Error).
The following conditions cause the number of bytes read to be less than count:
A. When reading a normal file, it is not enough count bytes to read to the end of the file. For example: If the file is only 30 bytes, and we want to read 100
BYTE, you actually read only 30 bytes, and the Read function returns 30. Using the Read function to effect this file at this time will cause read to return 0.
B. When reading from terminal equipment (terminal device), you can normally read only one row at a time.
C. When reading from the network, the network cache may cause the number of bytes read to be less than count bytes.
D. Read pipe or

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.