title: Reading from stdin by multiple processes
body: <p>I am writing a program in which the parent process uses <code>fork()</code> to create <code>N</code> child processes (N is provided as an argument), so that every child is directly forked by this one parent.</p>
  
  <p>Every child process needs to read a line from <code>stdin</code>, and print on to the screen.
  After compiling and executing the program, the text is provided through a text file like this:</p>
  
  <p><code>./prog1 3 &lt; fileWithText.txt</code></p>
  
  <p>My problem is, that I am expecting to see every child "fight" for reading the input, however what I actually see is that there is always only one child process taking care of handling the input. This is the code I use for the child process:</p>
  
  <pre><code>void do_child_reader(int j) {
    int pid;
    int counter = 0;
    char* buffer;
    char* readCheck;
    int readerRunning = TRUE;
  
    pid = getpid();
    buffer = (char*)malloc(BUFFER_SIZE * sizeof(char));
  
    while (readerRunning == TRUE) {
      readCheck = fgets(buffer, BUFFER_SIZE, stdin);
      if (readCheck == NULL) {
        readerRunning = FALSE;
      }
      else {
        fprintf(stdout, "(READER %d pid-%d) %s", j, pid, buffer);
        counter++;
      }
    }
  
    fprintf(stderr, "(READER %d pid-%d) processed %d messages, going to exit\n", j, pid, counter);
    free(buffer);
    exit(counter);
  }
  </code></pre>
  
  <p>Here's the output I get when running for N=3:</p>
  
  <pre><code>(READER 0 pid-72655) I am a message - line 1
  (READER 0 pid-72655) I am a message - line 2
  (READER 0 pid-72655) I am a message - line 3
  (READER 0 pid-72655) processed 3 messages, going to exit
  (READER 1 pid-72657) processed 0 messages, going to exit
  (READER 2 pid-72659) processed 0 messages, going to exit
  </code></pre>
  
  <p>The parent process is waiting for the children to finish before exiting.</p>
  
  <p>I am trying to figure out what would cause this behaviour, and whether it is in the way <code>fgets()</code> works or perhaps in the way I am trying to read the strings.</p>
  
  <p>Thank you!</p>