C ++ fork () - creating a "list" of processes

I have a program that creates new processes one by one. Is it possible to change this code so that it creates a "list" of processes - i.e. is child 1 a parent of child 2 and child 2 is a parent of child 3 etc.?

#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
source share
3 answers

Use fork in a set of nested 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; } 

Output

Parent PID 3857
child 1
child 2
child 3

For n processes

 #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; } 
+3
source

If you want to save the loop to dynamically set the depth of the fork tree,

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

Output

 My process id = 6596 Child #6597 Child #6598 Child #6599 Child #6600 
+3
source
 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; } 
-2
source

Source: https://habr.com/ru/post/1484127/


All Articles