C++ fork() -- 创建一个进程列表

4
我有一个程序,它会创建新的进程"一个接一个地"。是否可能改变此代码,使其创建一个进程"列表" - 即子进程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个进程,而是会创建2的4次方个进程。 - rjv
如果子进程1要成为子进程2的父进程,那么原始进程将不会知道关于子进程2的任何信息,除非子进程1或子进程2告诉它;对于子进程3和子进程4来说,这个问题更加严重。虽然子进程4可以知道所有祖先,但是它们的祖先不会知道他们最遥远的后代的任何信息。 - Jonathan Leffler
为什么要以线性、最远的方式创建进程层级结构呢?相反,单个父进程直接与其所有子进程相关可能更有用。这样,父进程可以拥有一个单一数组,存储所有子进程的PID,例如。在您所需的情况下,每个进程只知道一个父进程和一个子进程。额外的工作需要完成,以便通信他们所知道的内容或检查进程层次结构以发现完整的关系。 - wallyk
3个回答

4
如果您想保留循环以动态设置fork树的深度,
// 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

3

在一组嵌套的if语句中使用fork

#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;
}    

1
但是如果我想创建N个进程,该如何实现呢? - user2262230
嗨,我正在尝试做类似的事情。我想要生成它,直到达到可以创建的最大文件进程数量,并且无法再创建任何进程。在这种情况下我该怎么办? - shalki

-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;
}

请问您能否提供更多关于您所提供解决方案的细节? - abarisone

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接