I am experimenting with some problems with this code:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 30
#define Error_(x) { perror(x); exit(1); }
int main(int argc, char *argv[]) {
char message[SIZE];
int pid, status, ret, fd[2];
ret = pipe(fd);
if(ret == -1) Error_("Pipe creation");
if((pid = fork()) == -1) Error_("Fork error");
if(pid == 0){
close(fd[1]);
while( read(fd[0], message, SIZE) > 0 )
printf("Message: %s", message);
close(fd[0]);
}
else{
close(fd[0]);
puts("Tipe some text ('quit to exit')");
do{
fgets(message, SIZE, stdin);
write(fd[1], message, SIZE);
}while(strcmp(message, "quit\n") != 0);
close(fd[1]);
wait(&status);
}
}
The code is working fine, but I can’t explain why! There is no explicit synchronization between parent and child processes. If the child process is executed before the parent, the reading should return 0, and the process ends, but for some reason, it waits for the parent to complete. How do you explain this? Maybe I missed something.
(Edited)
source
share