I have a problem when writing a C program to print out the lines of a file. Suppose the file has 5 lines, it should create 5 child processes. Each child process reads a line from the file and prints the respective line.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#define BUFSIZE 256
#define ITR 1e6
int main(int argc, char *argv[]) {
if (argc != 2) exit(1);
pid_t pid;
char buffer[BUFSIZE] = { 0 }; // create buffer
FILE *fp = fopen(argv[1], "r"); // read file into *fp
while (fgets(buffer, BUFSIZE, fp)) {
pid = fork();
if (pid == 0) {
for (int j = 0; j < ITR; j++);
printf("%s\n", buffer);
_exit(0); // exit child
}
}
wait(NULL); // wait for child to finish
return 0;
}
The original file is
Child 1 reads this line\n
Child 3 reads this line\n
Child 2 reads this line\n
Child 4 reads this line\n
The output is listed below.
Child 1 reads this line\n
\n
Child 2 reads this line\n
\n
Child 3 reads this line\n
\n
Child 4 reads this line\n
\n
However I don't want the extra \n between two lines. So I modified printf("%s\n", buffer); to printf("%s", buffer); so there would be only 1 \n as in the original file. But the output turns to be
Child 1 reads this line
Child 2 reads this line
Child 3 reads this line
The last line which should be Child 4 reads this line didn't print out as I expected. Does anyone know why this would happen?