Reading from stdin by multiple processes

僤鯓⒐⒋嵵緔 提交于 2020-01-24 20:23:26

问题


I am writing a program in which the parent process uses fork() to create N child processes (N is provided as an argument), so that every child is directly forked by this one parent.

Every child process needs to read a line from stdin, and print on to the screen. After compiling and executing the program, the text is provided through a text file like this:

./prog1 3 < fileWithText.txt

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:

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

Here's the output I get when running for N=3:

(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

The parent process is waiting for the children to finish before exiting.

I am trying to figure out what would cause this behaviour, and whether it is in the way fgets() works or perhaps in the way I am trying to read the strings.

Thank you!


回答1:


If the file is so small that one unit of BUFSIZ (from <stdio.h>) bytes can be read by one process, the other processes have nothing left to read. Make the input file bigger — multiple times the size of BUFSIZ — and make sure the clients read slowly enough after getting a buffer full, and you will see them all working on it.

This is I/O buffering for you. You could try messing with setvbuf() to set line buffering on the input; I'm not sure it would work.



来源:https://stackoverflow.com/questions/34036642/reading-from-stdin-by-multiple-processes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!