I've written the code below. The parent process write
s one character at a time, followed by a sleep
call. The child process read
s one byte at a time and prints it immediately after reading.
However, I get all the output at once after waiting several seconds when I run this. I expected to get one character per second. Why is this?
(I know I could write the string all at once, but this is an experiment for the future.)
int fd[2];
pipe(fd);
pid_t pid = fork();
if (pid == 0) {
close(fd[WRITE_END]);
char *read_msg;
printf("Read: ");
// Read characters.
while (read(fd[READ_END], read_msg, 1)) {
printf("%c", *read_msg);
}
printf("\n");
close(fd[READ_END]);
} else {
close(fd[READ_END]);
char *msg = "Hello!";
char *c = msg;
// Write a character from parent every second.
while (*c) {
write(fd[WRITE_END], c++, 1);
sleep(1);
}
close(fd[WRITE_END]);
wait();
}