Where the process stops after exec () is called

Source: Internet
Author: User

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.
*/

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.