Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

fork() and execve

Status
Not open for further replies.

LaoMa

Programmer
Aug 24, 2002
10
US
I got 2 cod of parent.c and child.c here:
parent.c:

#include <sys/wait.h>
#define NULL 0
int main(void)
{
if(fork()==0){execve(&quot;child&quot;,NULL,NULL);exit(0);}
printf(&quot;Process[%d]:parent in execution\n&quot;,getpid());
sleep(2);
if(wait(NULL)>0)printf(&quot;Process[%d]:parent detects terminatin child&quot;,getpid());
printf(&quot;Process[%d]:parent terminating\n&quot;,getpid());
}

child.c:
int main()
{
printf(&quot;Process[%d]:child in execution\n&quot;,getid());
sleep(1);
printf(&quot;Process[%d]:child terminating\n&quot;,getid());
}


and the result of execution of parent.c is:
Parent in execution.
child in execution.
child terminating.
Parent detects terminating.
Parent terminating.



It was said that execve() makes the child program take place of the parent,so why
printf(&quot;Process[%d]:parent in execution\n&quot;,getpid());
was executed first?How could the whole procedure happen?
I'm vey confused.
Thanks a lot!
 
fork creates a second copy of the original program, for returns the pid of the child in the original copy of the program and returns 0 in the second copy of the program.

When you run execve() from the second copy of the program (or the child of the fork) then that copy is replaced by the program that was exec'ed.

I've added some comments to your code to show what is happening......

pid_t pid;

if((pid=fork())==0) /* The original program replicates here */
{
/* The child copy processes this path of code */
execve(&quot;child&quot;,NULL,NULL);
/* The child copy will never get to this point as it
will be replaced by the execed program. */
exit(0);
}
/* The original copy of the code will process here */
printf(&quot;Process[%d]:parent in execution.\n&quot;,getpid());
printf(&quot;Child [%d] was created\n&quot;,pid);
sleep(2);
if(wait(NULL)>0)
printf(&quot;Process[%d]:parent detects terminatin child&quot;,getpid());
printf(&quot;Process[%d]:parent terminating\n&quot;,getpid());


In your case the child.c code is actually more of grandchild rather than a child.

Does this help with your question?
Cheers - Gavin
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top