Giovanni Mauro Giovanni Mauro - 9 months ago 20
C Question

Create a chain of N processes where parent creates one child

I have to create four process, Every son has to create one son and just wait for it to finish.

PROCESS 0 --> PROCESS 1 --> PROCESS 2 --> PROCESS 3 --> PROCESS 4


How to do it ? I've tried the following so far:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <fcntl.h>
#define NUM_PROC 5


int main (void)
{
int pid;
int i;
int status;
for (i=0; i < NUM_PROC; i++)
{
if ((pid=fork()) <0 )
{
printf("Error in forking\n");
exit(EXIT_FAILURE);
} else if (pid ==0) {
printf("Sono: %d, mio padre e: %d\n", getpid(), getppid());
pid = fork();
}
else {
printf("Sono: %d, mio padre e: %d\n", getpid(), getppid());
wait( &status);
}
}
exit(EXIT_SUCCESS);
}

Answer Source

Main program is creating a new child process in the loop, which then runs the same loop as the parent and creates more child processes.

Using a for loop and generalizing for N processes:

for (int i=0; i<N; i++) 
{
    pid = fork();
    if (pid == -1) { // handle error }
    else if (pid == 0) {
        // son process (NO FORK INSIDE THIS ELSE IF!)
    }
    else { // parent process
        wait(NULL);
        exit(0);
    }
}