0% found this document useful (0 votes)
20 views

Unix Fork

The document describes a C++ program that uses fork and exec system calls to create child processes. The program forks twice - the first child prints its PID and exits, while the parent waits for it. The second child executes the ls command using execvp and the parent waits again.

Uploaded by

manish 123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Unix Fork

The document describes a C++ program that uses fork and exec system calls to create child processes. The program forks twice - the first child prints its PID and exits, while the parent waits for it. The second child executes the ls command using execvp and the parent waits again.

Uploaded by

manish 123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

4/16/2016

web.mst.edu/~ercal/284/UNIXforkexec/ForkExec2.cpp

#include<iostream>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>

usingstd::cout;
usingstd::endl;
usingstd::cerr;

intmain(intargc,char*argv[])
{
intpid=1;

//Createachildprocess
pid=fork();

if(pid==0)
{
cout<<endl<<"Iamthechild.Mypidis"<<getpid()<<"."<<endl;
return0;
}
elseif(pid>0)
{
cout<<endl<<"Iamtheparent.Mypidis"<<getpid()<<"."<<endl;
}
else
{
cerr<<"Forkerror.QuittingProgram."<<endl;

//Bailoutoftheprogram.
exit(EXIT_FAILURE);
}

//Theparentwillwaitforachildtodiebeforeproceeding.Thechild
//willnevergethere,becausethechildquitsintheifstatementabove.
wait(0);
cout<<endl<<"Childjustdied."<<endl;

//Now,thechildisdeadforsure,andwearebacktooneprocess.

cout<<endl<<endl;
cout<<endl<<"Startingphase2."<<endl;
cout<<endl<<endl;

//Forkaprocess,andhavethechildexecuteanls.
pid=fork();

if(pid==0)
{
cout<<endl<<"Iamthechild.Mypidis"<<getpid()<<"."<<endl;
cout<<endl<<"Thechildwillnowexecanlscommand."<<endl;

//Printalineofstarsabovethels.
cout<<"****************************************"
<<"****************************************"<<endl;
char*argm[]={"ls","la",0};

execvp(argm[0],argm);

cout<<"Thisstatementshouldnotbeexecutedifexecvpissuccessful."<<endl;
cerr<<"Theexeccommandissuedbythechildfailed!!!Exiting."
<<endl;
exit(EXIT_FAILURE);
}
http://web.mst.edu/~ercal/284/UNIXforkexec/ForkExec2.cpp

1/2

4/16/2016

web.mst.edu/~ercal/284/UNIXforkexec/ForkExec2.cpp

elseif(pid>0)
{
wait(0);

//Weknowforsurethatthechildisdead,soprintalineofstars
//afterthels.
cout<<endl<<"Parent:"<<"****************************************"
<<"****************************************"<<endl;
}
else
{
cerr<<"Forkerror.QuittingProgram."<<endl;

//Bailoutoftheprogram.
exit(EXIT_FAILURE);
}

return0;
}

http://web.mst.edu/~ercal/284/UNIXforkexec/ForkExec2.cpp

2/2

You might also like