Understanding of Process Creation in Linux (1)

Source: Internet
Author: User
A few days ago, our operating system teacher gave us a question about using fork to create a process.
The following program is referenced:

# Include <stdio. h>
# Include <stdlib. h>
# Include <unistd. h>

Int main ()
{
Int PID;
PID = fork ();

If (PID <0)
{
Fprintf (stderr, "fork failed/N ");
Exit (-1 );
}
Else if (pid = 0)
{
Execlp ("/bin/ls", null );
}
Else {
Wait (null );
Printf ("child complete/N ");
Exit (0 );
}

}

Then, add a sentence (for example, printf ("error/N") after the final statement (that is, after the if BLOCK statement); after the program is executed, two sentences will be printed.

After going back, I executed the following statement, but no error was found.
Why?
Fork () is a very interesting system function used to create a new process. It gives people the feeling that they have called once but returned two values. In the parent process, the child process ID is returned, and 0 is returned in the child process. That is, in this program, the PID value of the child process and the parent process is different. If a child process is successfully created, the PID value of the parent process is greater than zero, that is, the execution
Wait (null); wait until the sub-process is executed and
Printf ("child complete/N ");
Then exit through exit (0 );
The PID in the sub-process is 0, execlp ("/bin/ls", null) is executed, that is, execute ls to replace the execution image of the current process, the ls program will eventually call the exit function to end the process.
In the final if BLOCK statement, both the parent process and the child process exit, and the print statement is not added at the end.
If you want it to print two errors, you only need to remove the if statement block.

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.