Linux system programming-Process Control: Process Termination, waiting for Process Termination, linux Process

Source: Internet
Author: User

Linux system programming-Process Control: Process Termination, waiting for Process Termination, linux Process
End Process

First, let's review the functions of continue, break, and return in C:

Continue: end this cycle

Break: jump out of the entire loop or jump out of the switch () Statement

Return: end the current function.


But we can end the current process through exit () or _ exit.


Required header file:

# Include <stdlib. h>


Void exit (int value );

Function:

End the process of calling this function.

Parameters:

Status: the parameter returned to the parent process (which is effective at 8 low bits). Set this parameter as needed.

Return Value:

None


Required header file:

# Include <unistd. h>


Void _ exit (int value );

Function:

End the process of calling this function.

Parameters:

Status: the parameter returned to the parent process (which is effective at 8 low bits). Set this parameter as needed.

Return Value:

None


The functions and usage of the exit () and _ exit () functions are the same. The header files are different. The difference is that exit () is a standard library function, _ exit () is a function called by the system.


The following example verifies that calling the exit () function will refresh the I/O buffer (for more details about the buffer, see Introduction to the standard I/O buffer):

# Include <stdio. h> # include <stdlib. h> # include <unistd. h> int main (int argc, char * argv []) {printf ("hi, mike, you are so good"); // print, no linefeed "\ n" exit (0); // end the process, standard library function, refresh the buffer, and print the printf () content // _ exit (0 ); // end the process, the system calls the function, and the content of printf () is not displayed on the screen while (1); // do not let the program end return 0 ;}

The running result is as follows:



In the preceding example, call _ exit () when the process ends. The Code is as follows:

# Include <stdio. h> # include <stdlib. h> # include <unistd. h> int main (int argc, char * argv []) {printf ("hi, mike, you are so good"); // print, no linefeed "\ n" // exit (0); // The process is terminated, the standard library function is used, the buffer is refreshed, And the printf () content can be printed _ exit (0 ); // end the process, the system calls the function, and the content of printf () is not displayed on the screen while (1); // do not let the program end return 0 ;}

The content of printf () is not displayed. The running result is as follows:



Next, let's verify the difference between the end function (return) and the End Process (exit.


The test code is as follows:

# Include <stdio. h> # include <stdlib. h> # include <unistd. h> void fun () {sleep (2); return; // end the fun () function while (1);} int main (int argc, char * argv []) {fun (); printf ("after fun \ n"); while (1); // do not let the program end return 0 ;}

The running result is as follows:



According to the above running results,The function of return is to end the function that calls return.As long as this function is not the main function (main ()),As long as the main function does not end, return cannot end the process..


In the preceding example, change return in fun () to exit ():

# Include <stdio. h> # include <stdlib. h> # include <unistd. h> void fun () {sleep (2); exit (0); // end the current process while (1);} int main (int argc, char * argv []) {fun (); printf ("after fun \ n"); while (1); // do not let the program end return 0 ;}

Exit () is the process where you can end fun (). The result is as follows:



Wait for the process to end

When a process ends normally or abnormally, the kernel sends a SIGCHLD signal to its parent process, which is equivalent to telling the parent which son is down,The parent process can wait for the child process to end by using the wait () or waitpid () function to obtain the State at the end of the Child process and reclaim their resources.(This is equivalent to a father who listens to the last words of his dead son and buried it properly ).


The functions of wait () and waitpid () functions are the same. The difference is that the wait () function will be blocked, and waitpid () can be set to not blocked, waitpid () you can also specify the child process to wait for to end.


Required header file:

# Include <sys/types. h>

# Include <sys/wait. h>


Pid_t wait (int * status );

Function:

Wait until any sub-process ends. If any sub-process ends, this function recycles the resources of the sub-process (Resources mainly referThe resources of the kernel Process Control Block struct. For example, reclaim the process number so that other processes can reuse the number ).


The process that calls the wait () function suspends (blocks) until one of its sub-processes exits or receives a signal that cannot be ignored (equivalent to continuing to execute ).


If no sub-process exists in the called process, the function returns immediately. If its sub-process has ended, the function returns immediately and recycles the resources of the already terminated process.


Therefore, the main function of the wait () function is to recycle resources of child processes that have completed.


Parameters:

Status: status information when the process exits.


If the value of the status parameter is not NULL, wait () will take out the status when the sub-process exits and store it in it. This is an integer (int ), indicates whether the sub-process Exits normally or ends abnormally.


The exit information is included in an int.Multiple FieldsDirectly using this value is meaningless,We need to use a macro definition to retrieve each field..


Next, let's take a look at the two most common macro definitions and obtain the exit information of the sub-process:

WIFEXITED (status)

If the sub-process is terminated normally, the retrieved field value is non-zero.

WEXITSTATUS (status)

The exit status of the sub-process is returned ~ 16 bits. Before using this macro, use the macro WIFEXITED to determine whether the sub-process Exits normally.


Return Value:

Successful: Process number of the child process that has ended

Failed:-1


In essence, the functions of System Call waitpid () and wait () are exactly the same, but waitpid () has two more user-controlled parameters pid and options, this provides us with a more flexible way of programming.


Pid_t waitpid (pid_t pid, int * status, int options );

Function:

Wait for the sub-process to terminate. If the sub-process is terminated, this function recycles the sub-process resources.

Parameters:

Pid: The parameter pid has the following types:

Pid> 0

Wait for the child process whose process ID is equal to the pid.

Pid = 0

Wait for any sub-process in the same process group. If the sub-process has been added to another process group, the waitpid will not wait for it.

Pid =-1

Wait for any sub-process. At this time, the waitpid works the same as wait.

Pid <-1

Wait for any sub-process in the specified process group. the ID of this process group is equal to the absolute value of pid.


Status: status information when the process exits. Same as wait.


Options: options provides some additional options to control waitpid ().

0:

Same as wait (), blocking the parent process and waiting for the child process to exit.

WNOHANG;

If no child process has been completed, return immediately.

WUNTRACED:

If the sub-process is paused, the function returns immediately and ignores the end state of the sub-process. (Because it involves some tracking and debugging knowledge and is rarely used, there will be no extra money here. Interested readers can check the relevant materials on their own)

Return Value:

The return value of waitpid () is slightly more complex than that of wait (). There are three cases:


When the returned result is normal, waitpid () returns the process Number of the collected sub-process;


If the option WNOHANG is set, and waitpid () in the call finds that no child process has exited to wait, 0 is returned;


If an error occurs in the call,-1 is returned. errno is set to the corresponding value to indicate the error. For example, if the subprocess corresponding to the pid does not exist or the process exists, but not the sub-process that calls the process, waitpid () will return an error, and errno is set to ECHILD;


Test example:

# Include <stdio. h> # include <stdlib. h> # include <unistd. h> # include <sys/types. h> # include <sys/wait. h> int main (int argc, char * argv []) {pid_t pid; pid = fork (); // create process if (pid <0) {// error perror ("fork"); exit (0) ;}if (pid = 0) {// sub-process int I = 0; for (I = 0; I <5; I ++) {printf ("this is son process \ n"); sleep (1) ;}_ exit (2); // The sub-process exits, number 2: the sub-process exited status} else if (pid> 0) {// The parent process int status = 0; // wait until the sub-process ends, reclaim sub-process resources // This function will block // Status a field stores 2 of the _ exit (2) called by the sub-process. You need to use a macro definition to retrieve wait (& status); // waitpid (-1, & status, 0 ); // no difference from wait (), 0: Blocking // waitpid (pid, & status, 0); // specify the child process whose waiting process is pid, 0 blocking // waitpid (pid, & status, WNOHANG); // WNOHANG: Do not block if (WIFEXITED (status )! = 0) {// whether the sub-process terminates printf normally ("son process return % d \ n", WEXITSTATUS (status ));} printf ("this is father process \ n");} return 0 ;}

The running result is as follows:



Click here to download the sample code in this tutorial.

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.