[ prev |
next |
up ]
Reading from pipes
(regarding the attached program segment, below)
> Is it ok to read an empty pipe? It seems that when I try to read from
> an empty pipe, instead of getting -1 or 0 returned, the program halts.
> Can you tell me why?
Your program is halting because read() is, by default, a blocking system
call. Since you are reading from a pipe before anything has been written
to it, the read() call will wait indefinitely.
Try reversing the order of the read() and write() to see what happens.
- Jeremy
/* program.c */
#define MSG "hello, world"
#define MSG_LEN 13 /* number of characters plus 1 */
int main () {
int pfd[2]; /* pipe file descriptors */
char inbuf[MSG_LEN], outbuf[MSG_LEN];
int nbytes;
if (-1 == pipe(pfd)) {
perror ("pipe");
exit(1);
}
nbytes = read (pfd[0], inbuf, MSG_LEN);
if (MSG_LEN != nbytes) {
perror ("read did not receive message properly");
exit(1);
}
printf ("sent message to myself: %s\n", inbuf);
strcpy (outbuf, MSG, MSG_LEN);
nbytes = write (pfd[1], outbuf, MSG_LEN);
if (MSG_LEN != nbytes) {
perror ("write did not send message properly");
exit(1);
}
close (pfd[0]);
close (pfd[1]);
return 0;
}