I'm creating a program that runs on Linux and deals with getpid(), getppid(), fork(), wait(), and sleep() functions. For some reason, my cout lines duplicate in the output, and the bottom portion of my code doesn't run at all. I'm sure it has something to do with the other exit codes, but I'm not sure how to fix it. Can anyone help me?
int main()
{
pid_t pid, childpid;
cout<<"The beginning process name is "<<getpid()<<endl;//gets and prints the main process
cout<<"The beginning parent process is "<<getppid()<<endl<<endl;//gets and prints the parent process
pid = fork();//creates 2 processes (parent and child)
childpid = fork();//creates 2 processes (child and grandchild)
//If the parent fork fails, print an error message and exit
if(pid < 0)
{
cerr<<"A fork error occurred. Ending program."<<endl;
exit(-1);
}
else
{
//Print the id of the child and parent process id
cout<<"This is in the child process, PID of "<<getpid()<<endl;
cout<<"The parent PID of the child process is "<<getppid<<endl;
if(childpid < 0)
{
//if the child fork fails, print an error message and exit
cerr<<"The second fork failed."<<endl;
exit(-1);
}
else
{
//print the grandchild and child ids and exit from grandchild.
cout<<"We're in the grandchild process, value of "<<getpid()<<"."<<endl;
cout<<"The PID of grandchild's parent is "<<getppid()<<"."<<endl;
cout<<"We will now exit the program from grandchild."<<endl;
exit(0);
}
cout<<"This is the child process, PID of "<<getpid()<<endl;
cout<<"The parent PID is "<<getppid()<<endl;
wait(0);//wait for grandchild to terminate
cout<<"We're about to exit the child process."<<endl;
exit(0);//exit from child
}
cout<<"This is the parent process, ID of "<<getpid()<<endl;
cout<<"The parent of the parent is "<<getppid()<<endl;
sleep(2);//sleep for 2 seconds
cout<<"Parent is awake and will now call the ps function."<<endl;
system("ps");//call the ps Linux command
wait(0);//wait for child to terminate
cout<<"Ending parent, about to terminate."<<endl;
exit(0);//exit from parent
Do you realize that when your program encounters exit() the program stops and exits to the operating system and none of the code following the exit() is executed?