C:如何在子进程末尾打印父进程?

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

如何修改这段代码,让父进程打印出它的信息,毕竟子进程执行完了。

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

要将 parent 进程与 child 进程同步,您需要使用 waitwaitpid

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

从简单开始,您可以在一个循环中调用 wait,该循环将迭代与您希望等待的 children 数量相同的次数。在你完成所有 children 的生成之后,也许沿着这些思路可以让你开始:

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