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!