Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

modify the program so that the new children do not create additional processes,

ID: 3603466 • Letter: M

Question

modify the program so that the new children do not create additional processes, i.e., so that only the original parent calls fork. Keep the printf call for all processes. Before,

If we run parentcreats 1, two processes are created, the original parent process and its child. Assuming the process id of the parent is 414 and the process id of the child is 416, we can represent the relationship between these processes using the following ASCII diagram:

parentcreates 3 is run. Note that the child process ids will not necessarily be in sequence. 414 416 414 -417 414 -> 420

Explanation / Answer

// CODE

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>

/************* ALGORITHM ******************
-> A call to fork() returns -1 for failure, 0 to the child process and a positive number to the parent

-> These return values can be used to control what section of code is executed in the parent and child process
******************************

*************/

int main(int argc, char **argv) {
   int i;
   //
   int iterations;
   //
   if (argc != 2)
   {
       //
       fprintf(stderr, "Usage: forkloop<iterations> ");
       //
       exit(1);
   }
   //
   iterations = strtol(argv[1], NULL, 10);
   //
   for(i = 0; i < iterations; i++)
   {
       // call the fork here
       int n = fork();

       // fork() returns a positive number to parent
       ///
       if(n < 0){
           //
           perror("fork");
           //
           exit(1);
       }
       //
       // fork() returns 0 to child, now the child executes only the statements inside this if block, so does not fork()
       if (n == 0){
        printf("ppid = %d, pid = %d, i = %d ", getppid(), getpid(), i);
        //
        exit(0); // return from child
       }

       sleep(1); // wait some time before creating a new process, may be removed or changed
   }
   //
   sleep(1);
   //
   return 0;

}