【问题标题】:How can i Modify this program so that the child process creates another child?我怎样才能修改这个程序,以便子进程创建另一个子进程?
【发布时间】:2017-06-12 08:23:19
【问题描述】:

修改下面的程序,让子进程创建另一个子进程并等待它。孙子打印出自己的 id,它的父母和祖父母。

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

//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 ); 

}

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

【问题讨论】:

  • 你为什么要发送垃圾邮件?这是C++ 代码。

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


【解决方案1】:
    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;  
        }

【讨论】:

  • 所以对于我已经注释掉 'if(pid == 0)' 的 if 语句,然后在其中创建一个 fork 对吗?
  • :) 我没有看到开关下面的代码部分;创建过程有效,但我建议您使用getpid()getppid() 来获取执行该函数的运行进程的pid 及其父pid。我会相应地编辑我的答案。
猜你喜欢
  • 1970-01-01
  • 2020-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多