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