Where the process stops after exec () is called
[Cpp]
# Include <unistd. h>
# Include <stdlib. h>
# Include <stdio. h>
# Include <errno. h>
Int main ()
{
Int a = 1;
Int pid;
Char buff [] = "before fork ";
If (write (1, buff, sizeof (buff)-1 )! = (Sizeof (buff)-1 ))
{
Perror ("write error ");
Exit (0 );
}/* The code before fork will not be executed in the sub-process */
If (pid = fork () =-1)
{
Perror ("fork error ");
Exit (1 );
}
Else if (pid = 0)
{
If (execlp ("./write1", "write1", (char *) 0) =-1)
{
Perror ("execlp error ");
Exit (1 );
}/* The exec function replaces the process space of the process, and the process is terminated after execution. Therefore, the following two lines of code will not be executed */
************** ***************/
A ++;/* not executed */
Printf ("% d", a);/* not executed */
}
If (execlp ("./write1", "write1", (char *) 0) =-1)
{
Perror ("execlp error ");
Exit (1 );
}
************** ***************/
Printf ("% d", a);/* Similarly, this line of code will not be executed */
Return 0;
}
/* The write1 program called by execlp above */
# Include <unistd. h>
# Include <stdlib. h>
# Include <stdio. h>
# Include <errno. h>
Int main ()
{
Char buff [] = "write ";
If (write (1, buff, sizeof (buff)-1 )! = (Sizeof (buff)-1 ))
{
Perror ("write error ");
Exit (1 );
} Www.2cto.com
Return 0;
}
/*
Summary:
1. The code before fork will not be executed in its subprocesses. The reason may be that fork copies the process space at the moment when fork is called, and the code before fork has vanished in the stack.
2. The Program executed by the exec function replaces the process space of the process, and the process is terminated after execution, so the code after exec is not executed.
*/