我如何修改此程序,以便子进程创建另一个子进程?

时间:2017-01-26 18:42:55

标签: c++ process operating-system fork wait

修改以下程序,以便子进程创建另一个子进程并等待它。这个大孩子打印出自己的身份,父母和祖父母。

这是我迄今为止尝试过的......

//testWait.cpp
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

int main()
{
pid_t pid;      //process id
string message;
int n;
int exit_code;

cout << "fork program starting\n";
pid = fork();
switch ( pid ) 
{
case -1:
  cout << "Fork failure!\n";
  return 1;
case 0:
  message = "This is the child\n";
  n = 5;
  exit_code = 9;
  break;
default:
  message = "This is the parent\n";
  n = 3;
  exit_code = 0;
  break;
}

for ( int i = 0; i < n; ++i ) 
{
    cout << message;
    sleep ( 2 );
}

//waiting for child to finish
if ( pid > 0 )   //parent 
{       
    int stat_val;
    pid_t child_pid;

    child_pid = wait ( &stat_val ); //wait for child 
    cout << "Child finished: PID = " << child_pid << endl;
    if ( WIFEXITED ( stat_val ) )   //rerturn true if child terminated  normally that is by exit(3)
        cout << "child exited with code " << WEXITSTATUS ( stat_val ) << endl;  //returns the exit status of the child.
    else
        cout << "child terminated abnormally!" << endl;
}
/*
if(pid == 0)       //child
{
    int stat_val;
    pid_t gc_pid, pid2; 
    pid2 = fork();
    //gc_pid = fork();
    gc_pid = wait ( &stat_val );    //wait for grandchild
    if(pid2 == 0)
    {
        cout << "This is the GrandChild\n";
        exit_code = 9;
        cout << "GrandChild finished: PID = " << gc_pid << endl;
        //cout << "My parent is PID = " << pid;
    }
    //cout << "GrandChild finished: PID = " << gc_pid << endl;  
}
*/


exit ( exit_code ); 

}

我注释掉的代码部分是我尝试过的。

1 个答案:

答案 0 :(得分:0)

    if(pid == 0)       //child
        {
        int stat_val;
        pid_t gc_pid, pid2; 
        pid2 = fork();
        //gc_pid = fork();
        gc_pid = wait ( &stat_val );    //wait for grandchild
        if(pid2 == 0)
            {
             cout << "This is the GrandChild\n";
             exit_code = 9;
             cout << "GrandChild finished: PID = " << getpid() << endl;
             cout << "My parent is PID = " << getppid()<< endl;
            }
        cout << "GrandChild finished: PID = " << getpid() << endl;  
        }