Key points for using functions such as zombie process, orphan process, wait, exit, and execl

Source: Internet
Author: User

Process 1 is the main first process init of all processes

How to view the process: PS uax

# Include <sys/types. h>
# Include <unistd. h>
# Include <stdio. h>
# Include <stdlib. h>

Int main ()
{
Pid_t PID;
Int A = 8;
Printf ("current process ID: % d \ n", getpid ());
PID = fork ();
If (pid> 0) // What the parent process does
{
Printf ("A = % d \ n", );
Printf ("pid = % d \ n", pid); // sub-process
Printf ("ppid = % d \ n", getpid (); // parent process
// While (1 );
} Else if (pid = 0) // tens of thousands of sub-Processes
{
A ++;
Printf ("AA = % d \ n", );
Printf ("Child pid = % d \ n", getpid (); // sub-process
Printf ("parent pid = % d \ n", getppid (); // parent process
// While (1 );
} Else {
Printf ("fork error! \ N ");
}

Exit (0 );
}
/*
* Fork function:
* 1. The fork function is used to create sub-processes. Sub-Process
* Inherits all statuses run before the parent process and
* Copy the address space of the parent process to become the parent
* A copy of the process. Sub-process from fork Function
.
* 2. The fork function cannot guarantee the parent process and child process.
* Which runs first.
* Two processes are executed, so the result is six.
*/

Result:

Current process ID: 1995
A = 8
PID = 1, 1996
Ppid = 1995
AA = 9
Child pid = 1996
Parent pid = 1995


Generation of zombie processes:

/*
========================================================== ==========================================
Name: jianshiprocess. c
Author:
Version:
Copyright: Your copyright notice
Description: Hello world in C, ANSI-style
========================================================== ==========================================
*/
// Zombie Process
# Include <stdio. h>
# Include <stdlib. h>
# Include <unistd. h>
# Include <sys/types. h>
// Zombie process:
// The child process exits before the parent process. At this time, the child process becomes a zombie process.
// Orphan process:
// The parent process exits before the child process. At this time, the child process becomes an orphan process. The child process is not supported by the INIT process. (that is, the INIT process becomes the parent process of the child process, the INIT process is the parent process of all orphan processes)
// Both must be avoided.

Int main (void)
{
Pid_t PID;
PID = fork ();
If (pid> 0)
{
Sleep (10); // wake up the parent process
}
Else if (pid = 0)
{
Printf ("child % d", getpid ());
Printf ("P % d", getppid ());
Exit (0); // After the zombie process becomes a zombie process, the process is occupied.
}
Else
{
Puts ("wrong ");
Exit (0 );
}
Return exit_success;
}

Orphan process:


/*
========================================================== ==========================================
Name: guerprocess. c
Author:
Version:
Copyright: Your copyright notice
Description: Hello world in C, ANSI-style
========================================================== ==========================================
*/

# Include <stdio. h>
# Include <stdlib. h>
# Include <unistd. h>
# Include <sys/types. h>
Int main (void ){
Int I;
Pid_t PID;
Printf ("current process ID: % d \ n", getpid ());
PID = fork ();

If (pid> 0)
{
Exit (0); // After the zombie process becomes a zombie process, the process is occupied.
}
Else if (pid = 0)
{
For (I = 0; I <20; I ++)
{
Printf ("Child: % d \ n", getpid ());
Printf ("parent: % d \ n", getppid ());
}
}
Else
{
Puts ("wrong ");
Exit (0 );
}
Return exit_success;
}

Strange phenomenon: if the program is blocked by pressing CTRL + C during the execution of the process, the child process becomes an orphan process, the main process daemon, because its parent process is the INIT process, and CTRL + C can only stop the program running on the foreground



2:

Difference between return and exit:

Return is used for function return. The process exits only when the main function is called.

The exit function is called and the process exits directly.


The similarities between exit and _ exit are as follows:

Are used to exit the process.

Differences:

The exit function refreshes the file buffer to the file before the process exits.

_ Exit does not refresh the buffer before the process exits, that is, directly discards the content in the buffer.


Fork and vfork

When fork is executed to create a child process, the child process copies the data segment, heap segment, and stack segment of the parent process. At this time, the data of the Parent and Child processes is consistent and independent of each other, without affecting each other, the processing of data by sub-processes does not affect the parent process. (In fact, when the parent and child processes do not perform write operations on the three segments, the Parent and Child processes still share the data segment, heap segment, and stack segment. When either side has a write operation, a copy is generated, in this way, write is a copy)

There are two differences between vfork and fork: 1. The child process created by vfork shares the data segment with the parent process. 2. The child process created by vfork takes precedence over the parent process. When the child process is executed, the parent process is blocked.

Therefore, the data modification of the child process generated by vfork will certainly affect the data of the parent process.

 

Exit and _ exit

Exit: When exit is executed, terminate the processing program, execute the standard I/O clear operation (write files in the cache), call atexit, and call _ exit. It can be seen that exit is an enhanced version of _ exit.

_ Exit: notifies the kernel that the process has ended.

Code differences:

Printf ("hello ");

Exit (0 );//

Result: The output is hello, and the buffer is refreshed.

Printf ("hello ");

_ Exit (0)

Result: The content in the buffer zone is discarded without output.

3. Wait functions:

Wait (waiting for the sub-process to be interrupted or terminated)
Related functions Waitpid, fork
Header file # Include <sys/types. h>
# Include <sys/Wait. H>
Define functions Pid_t wait (int * status );
Function Description Wait () temporarily stops the execution of the current process until a signal arrives or the child process ends. If the child process has ended when wait () is called, wait () immediately returns the child process end status value. The end status value of a sub-process is returned by the status parameter, and the process identifier of the sub-process is returned quickly. If you do not care about the end status value
Parameters Status can be set to null. For the end status values of sub-processes, see waitpid ().
Return Value If the execution is successful, the sub-process identifier (PID) is returned. If an error occurs,-1 is returned. The cause of failure is stored in errno.

Notes:

1. The process calling the wait function is blocked directly.

2. It is generally called by the parent process to recycle the resources occupied by the child process when it exits, so as to avoid it from becoming a zombie process.

3. If a process calls this function without any sub-processes, the wait function returns

4. Signal Processing (when the sub-process status changes, the kernel will send a signal to its parent process, and the user process will ignore this signal by default)

5. Exit any sub-process that calls the wait function process. This function returns. (Or exit if the sigchlorophyll function is found)

6. Obtain the status value of the sub-process wait (& Status)

For example, exit (7) and 7 are Integer constants, which occupy 32 bits. Take the lower eight bits of the Integer constants and place them in the higher eight bits of the 32-bit status, if you shift the value of status to the right eight bits, it becomes 7 again (status is an integer variable) because its low eight bits will be occupied by other semaphores. (the value in exit can only be 0-255)

A wait instance can only recycle the space of one sub-process.

7. A specified sub-process cannot be recycled.



Once a process calls wait, it immediately blocks itself. Wait automatically analyzes whether a sub-process of the current process has exited. If it finds such a sub-process that has become a zombie, wait will collect information about this sub-process and destroy it completely and return it. If such a sub-process is not found, wait will be blocked until one appears.

The status parameter is used to save some statuses when the collection process exits. It is a pointer to the int type. But if we don't care about how this sub-process died, we just want to destroy it (in fact, in most cases, we will think like this ), we can set this parameter to null, as shown below

  1. PID = wait (null );

If the call succeeds, wait returns the ID of the collected sub-process. If the call process does not have a sub-process, the call fails. In this case, wait returns-1 and errno is set to echild.

If the value of the status parameter is not null, wait will take out the status of the sub-process and store it in it. This is an integer (INT ), it indicates whether the sub-process Exits normally or is ended abnormally (a process can also be ended by another process with a signal, which will be introduced in future articles ), and the return value at the normal end, or information about which signal is terminated. Because the information is stored in different binary bits of an integer, It is very troublesome to read it using the conventional method. People have designed a special macro (macro) to complete this work, next, let's take a look at two of the most common ones:

1. The wifexited (Status) macro is used to indicate whether the sub-process Exits normally. If yes, it returns a non-zero value.

(Please note that, although the name is the same, the parameter status here is not the only parameter of wait -- the pointer to the integer status, but the integer pointed to by the pointer. Remember not to confuse it .)

2. wexitstatus (Status) When wifexited returns a non-zero value, we can use this macro to extract the return value of the sub-process. If the sub-process calls exit (5) to exit, wexitstatus (Status) 5 is returned. If the sub-process calls exit (7), wexitstatus (Status) returns 7. Note that if the process does not exit normally, that is, if wifexited returns 0, this value is meaningless.

/*
========================================================== ==========================================
Name: Wait. c
Author:
Version:
Copyright: Your copyright notice
Description: Hello world in C, ANSI-style
========================================================== ==========================================
*/
// Mostly used in parent and multi-process
# Include <stdio. h>
# Include <stdlib. h>
# Include <sys/types. h>
# Include <sys/Wait. H>
# Include <unistd. h>

Int main (void ){
Pid_t PID;
Int status;
PID = fork ();
If (pid> 0)
{
Wait (& status );
Printf ("this is a parent process \ n ");
If (wifexited (Status ))
{
Printf ("status is % d \ n", wexitstatus (Status ));
}
Exit (0 );
}
Else if (pid = 0)
{
Printf ("this is a child process! \ N ");
Exit (7 );
}
Else
{
Printf ("fork error! \ N ");
Exit (1 );
}
Return exit_success;
}
4. wait_pid



Waitpid (waiting for sub-process interruption or termination)
Related functions Wait, fork
Header file # Include <sys/types. h>
# Include <sys/Wait. H>
Define functions Pid_t waitpid (pid_t PID, int * status, int options );
Function Description Waitpid () will temporarily stop the execution of the current process until a signal arrives or the child process ends. If the child process has ended when wait () is called, wait () immediately returns the child process end status value. The end status value of a sub-process is returned by the status parameter, and the process identifier of the sub-process is returned quickly. If you do not care about the end status value, you can set the parameter status to null. The PID parameter is the identifier of the child process to wait. Other values are as follows:
PID <-1 any child process that waits for the Process Group Identifier to be the absolute value of the PID.
PID =-1 waits for any sub-process, which is equivalent to wait ().
PID = 0 wait for any sub-process with the same process ID as the current process.
PID> 0: Wait for any sub-process whose ID is PID.
The option parameter can be 0 or an or combination below.
If wnohang does not have any child process that has ended, it will return immediately and will not wait.
Wuntraced: If the sub-process is paused, it will return immediately, but the end state will not be ignored.
The sub-process end status is returned and stored in status. There are several macros under it to determine the end status.
Wifexited (Status) is not 0 if the sub-process ends normally.
Wexitstatus (Status) gets the end code returned by the sub-process exit (). Generally, wifexited is used to determine whether the macro can be used until it ends normally.
Wifsignaled (Status) If the sub-process ends because of a signal, the macro value is true.
Wtermsig (Status) gets the signal code of the sub-process terminated due to the signal. Generally, this macro is used only after wifsignaled is used for determination.
Wifstopped (Status) If the sub-process is paused, the macro value is true. This is generally the case only when wuntraced is used.
Wstopsig (Status) gets the signal code that causes the sub-process to pause. This macro is generally used only after wifstopped is used for determination.

Wait_pid (PID, & status, 0); // wait for the specified sub-process to recycle the specified sub-process

Execl:




Execl (Execution file)
Related functions Fork, execle, execlp, execv, execve, execvp
Header file # Include <unistd. h>
Define functions Int execl (const char * path, const char * Arg ,....);
Function Description Execl () is used to execute the file path represented by the path string parameter. The following parameter indicates that the previous argv (0), argv [1]…, The last parameter must end with a null pointer.
Return Value If the execution is successful, the function will not return. If the execution fails,-1 will be returned. The cause of the failure is stored in errno.
Example # Include <unistd. h>
Main ()
{
Execl ("/bin/ls", "ls", "-Al", "/etc/passwd", (char *) 0 );
}
Run /* Run/bin/LS-Al/etc/passwd */
-RW-r -- 1 Root 705 Sep 3 13: 52/etc/passwd

The statement after execution is likely to be erased, and the previous statement is still

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.