I am using a subroutine named read_from_pipe
in my child
process as below to read whatever is in the pipe and display it:
void read_from_pipe(int fileDescriptr)
{
FILE *stream;
int c;
if (fileDesc_Is_Valid(fileDescriptr) == TRUE)
{
stream = fdopen(fileDescriptr, "r");
while ((c = fgetc(stream)) != EOF)
putchar(c);
fclose(stream);
}
else
perror("Reading from pipe failed -->");
}
fileDesc_Is_Valid
is another subroutine which checks the existance of file descriptor.
The problem is that because I have used waitpid(pid, &status, 0);
statement in my parent
to wait for child
to finish off its tasks, the compiler gets stuck in the first cold run at while
loop when pipe is actually empty. How can I AND
another condition in my while
to let compiler simply ignore empty pipes?
It's actually very simple, you just need to ignore the SIGPIPE
signal, and it's done with a single function-call:
signal(SIGPIPE, SIG_IGN);
When the pipe is empty, instead of raising the SIGPIPE
signal, reading from the pipe will return an end-of-file value (the underlying read
system-call will return 0
).