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.