I have this code:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <signal.h>
#define READ 0
#define WRITE 1
char* phrase = "Hello";
void PIPE(){
int fd [2], bytesRead;
char message [100]; /* Parent process' message buffer */
pipe (fd); /*Create an unnamed pipe */
if (fork () == 0) /* Child, writer */
{
close(fd[READ]); /* Close unused end */
write (fd[WRITE],phrase, strlen (phrase) + 1);
close (fd[WRITE]); /* Close used end*/
}
else /* Parent, reader*/
{
close (fd[WRITE]); /* Close unused end */
bytesRead = read (fd[READ], message, 100);
printf ("Read %d bytes: %s\n", bytesRead, message); /* Send */
close (fd[READ]); /* Close used end */
}
}
I'm studying the Pipe in C , and my book says:
If a process reads from a pipe whose write end has been closed, the read () returns a 0, indicating end-of-input.
but in the code(in the parent part) , before read function the write part has close and the read function doesn't return 0 but 5(lenght of Hello).
what is wrong?
thank for your time
UPDATE 1:
I have another question for you(I understand the first problem ):
at the beginning if the reader reads empty pipe, the read function returns 0, but how can I be sure this is the first writer to start and then after the reader ?
It should include "once all written data has been read". Otherwise a pipe would not make much sense. Or would require to explicitly signal to the writer the reader has taken all data from the pipe before closing - breaking its file semantics.