5

我有一个“一个接一个”创建新进程的程序。是否可以更改此代码以创建一个进程“列表”——即子 1 是子 2 的父,子 2 是子 3 的父,等等?

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

using namespace std;
int main ()
{
 pid_t pid;
 int i;

 cout << "My process id = " << getpid() << endl;

 for (i = 1; i <= 4; i++)
  switch ( pid = fork() ) {
  case -1:
    syserr("Error in fork");

  case 0:
    cout << "Child process: My process id = " << getpid() << endl;
    cout << "Child process: Value returned by fork() = " << pid << endl;
    return 0;

  default:
    cout << "Parent process. My process id = " << getpid() << endl;
    cout << "Parent process. Value returned by fork() = " << pid << endl;

   if (wait(NULL) == -1) 
   syserr("Error in wait");

 }  
 return 0;
 }
4

3 回答 3

4

如果要保持循环以动态设置树的深度,

// Set DEPTH to desired value

#define DEPTH 4

int main ()
{
  pid_t pid;
  int i;

  cout << "My process id = " << getpid() << endl;

  for (i=1 ; i <= DEPTH ; i++) {

    pid = fork();    // Fork

    if ( pid ) {
       break;        // Don't give the parent a chance to fork again
    }
    cout << "Child #" << getpid() << endl; // Child can keep going and fork once
  }

  wait(NULL);        // Don't let a parent ending first end the tree below
  return 0;
}

输出

My process id = 6596
Child #6597
Child #6598
Child #6599
Child #6600
于 2013-06-03T06:00:13.740 回答
3

fork在一组嵌套if的 s中使用

#include<stdio.h>
int main()
{   
printf("Parent PID %d\n",getpid());
if(fork()==0)
{
    printf("child 1 \n");
    if(fork()==0)
    {
        printf("child 2 \n");
        if(fork()==0)
            printf("child 3 \n");
    }

}
return 0;
}    

输出

父母 PID 3857
孩子 1
孩子 2
孩子 3

对于 n 个进程,

#include<stdio.h>
void spawn(int n)
{
if(n)
{
    if(fork()==0)
    {
        if(n)
        {
            printf("Child %d \n",n);
            spawn(n-1);
        }
        else
            return;
    }
}
}
int main()
{   
printf("Parent PID %d\n",getpid());
int i=0;
spawn(5);
return 0;
}    
于 2013-06-03T05:49:02.963 回答
-2
int make_proc(int counter, int parent){
pid_t x=getpid();
std::cout << counter << " process "<< x << " : parent" << parent<< std::endl;


    if (counter==0) {
       return 1;
    }
    else {
        counter=counter-1;
        pid_t pid=fork();
       if (pid==0) return make_proc(counter, x);
       wait(NULL);

    }

}

--------------------

int main(int argc, char **argv)
{
    int x=getpid();
    make_proc(10, x);
    return 0;
}
于 2015-06-11T19:10:35.010 回答