Avoiding a fork()/SIGCHLD race condition

后端 未结 4 1156
情话喂你
情话喂你 2020-12-17 16:12

Please consider the following fork()/SIGCHLD pseudo-code.

  // main program excerpt
    for (;;) {
      if ( is_time_to_make_babie         


        
4条回答
  •  无人及你
    2020-12-17 16:23

    In addition to the existing "children" add a new data structure "early deaths". This will keep the contents of children clean.

      // main program excerpt
        for (;;) {
          if ( is_time_to_make_babies ) {
    
            pid = fork();
            if (pid == -1) {
              /* fail */
            } else if (pid == 0) {
              /* child stuff */
              print "child started"
              exit
            } else {
              /* parent stuff */
              print "parent forked new child ", pid
              if (!earlyDeaths.contains(pid)) {
                  children.add(pid);
              } else {
                  earlyDeaths.remove(pid);
              }
            }
    
          }
        }
    
      // SIGCHLD handler
      sigchld_handler(signo) {
        while ( (pid = wait(status, WNOHANG)) > 0 ) {
          print "parent caught SIGCHLD from ", pid
          if (children.contains(pid)) {
              children.remove(pid);
          } else {
              earlyDeaths.add(pid);
          }
        }
      }
    

    EDIT: this can be simplified if your process is single threaded -- earlyDeaths doesn't have to be a container, it just has to hold one pid.

提交回复
热议问题