Search code examples
cmultithreadingprocess-management

C: How to print parent process at the end of child?


How to modify this code so that the parent process prints out its information, after all, child process done with execution.

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

    int main (int argc, char *argv[]) {
       pid_t childpid = 0; 
       int i, n;

       if (argc != 2){   /* check for valid number of command-line arguments */ 
          fprintf(stderr, "Usage: %s processes\n", argv[0]);
          return 1; 
       }     
       n = atoi(argv[1]);  
       for (i = 1; i < n; i++)
          if ((childpid = fork()) <= 0)
             break;

       fprintf(stderr, "i:%d  process ID:%ld  parent ID:%ld  child ID:%ld\n",
               i, (long)getpid(), (long)getppid(), (long)childpid);
       return 0; 
    }

Solution

  • To synchronize a parent process with child processes, you want to make use of wait or waitpid

    https://linux.die.net/man/3/wait

    To start off simple, you could call wait in a loop that would iterate as many times as the number of children you spawned that you wish to wait for. Perhaps something along these lines after you've finished spawning all the children could get you started:

    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/wait.h>
    #include <unistd.h>
    
    int main (int argc, char *argv[]) {
       pid_t childpid = 0; 
       int i, n;
    
       if (argc != 2){   /* check for valid number of command-line arguments */ 
          fprintf(stderr, "Usage: %s processes\n", argv[0]);
          return 1; 
       }     
       n = atoi(argv[1]);  
       for (i = 1; i < n; i++)
             if ((childpid = fork()) <= 0)
                break;
    
       if (childpid>0){ // parent process
           while (i>1) {
               wait(NULL);
               i--;
           }
       }
    
       fprintf(stderr, "i:%d  process ID:%ld  parent ID:%ld  child ID:%ld\n",
               i, (long)getpid(), (long)getppid(), (long)childpid);
       return 0;
    }