5

新しいプロセスを「1つずつ」作成するプログラムがあります。プロセスの「リスト」を作成するようにこのコードを変更することは可能ですか?つまり、子 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使用する

#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 に答える