Unix Fork
Unix Fork
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