Creating multiple children of a process and maintaining a shared array of all their PIDs

前端 未结 1 1739
余生分开走
余生分开走 2021-01-29 02:50

I have forked a couple of times and have created a bunch of child processes in C. I want to store all their PIDs in a shared array. The ordering of the PIDs does not matter. For

1条回答
  •  清酒与你
    2021-01-29 03:27

    Here's a program that illustrates what you want using mmap():

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    #define MAX_PIDS 32
    
    volatile pid_t *pids;
    
    // Called for each child process
    void do_child(void)
    {
      int c;
      printf("Child: %d - pid array: ", getpid());
    
      for (c=0; c<10; c++) {
        printf("%d%s", pids[c], c==9?"\n":" ");
      }
    }
    
    int main(int argc, char **argv)
    {
      int c;
      pid_t pid;
    
      // Map space for shared array
      pids = mmap(0, MAX_PIDS*sizeof(pid_t), PROT_READ|PROT_WRITE,
                  MAP_SHARED | MAP_ANONYMOUS, -1, 0);
      if (!pids) {
        perror("mmap failed");
        exit(1);
      }
      memset((void *)pids, 0, MAX_PIDS*sizeof(pid_t));
    
      // Fork children
      for (c=0; c<10; c++) {
        pid = fork();
        if (pid == 0) {
          // Child process
          do_child();
          exit(0);
        } else if (pid < 0) {
          perror("fork failed");
        } else {
          // Store in global array for children to see
          pids[c] = pid;
          sleep(1);
        }
      }
      exit(0);
    }
    

    0 讨论(0)
提交回复
热议问题