Problem forking fork() multiple processes Unix

后端 未结 4 1096
走了就别回头了
走了就别回头了 2021-02-01 23:28

So I have this function that forks N number of child processes. However it seems to be forking more than specified. Can you tell me what I\'m doing wrong? Thanks



        
4条回答
  •  遥遥无期
    2021-02-01 23:55

    In this exercise I'd use recursion rather than a for loop. This way you can have the fork() instruction called multiple times but just on one of the two copies of the process. You can make the child process spawn another child process, thus having grandparents, grand-grandparents etc. or you can call the fork() on the parent side, having a single "father" and multiple children. This is a sample of code which implements the latter solution:

    #include 
    #include 
    #include 
    
    int nChildren;
    
    void myFork(int n);
    
    int main(int argc, char *argv[]) {
    
      // just a check on the number of arguments supplied
      if (argc < 2) {
        printf("Usage: forktest \n");
        printf("Example: forktest 5 - spawns 5 children processes\n");
        return -1;
      }
    
      nChildren = atoi(argv[1]);
      // starting the recursion...
      myFork(nChildren-1);
      return 0;
    }
    
    // the recursive function
    void myFork(int n) {
      pid_t pid;
    
      pid = fork();
    
      // the child does nothing but printing a message on screen
      if (pid == 0) {
        printf("I am a child: %d PID: %d\n", nChildren-n, getpid());
        return;
      }
    
      // if pid != 0, we're in the parent
      // let's print a message showing that the parent pid is always the same...
      printf("It's always me (PID %d) spawning a new child (PID %d)\n", getpid(), pid);
      // ...and wait for the child to terminate.
      wait(pid);
    
      // let's call ourself again, decreasing the counter, until it reaches 0.
      if (n > 0) {
        myFork(n-1);
      }
    }
    

提交回复
热议问题