Readings
Simple example of using pipe
#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);
}
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);
}
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);
close (pfd[0]);
close (pfd[1]);
return 0;
}
- this is silly; process doesn't need to send itself a message
- but very useful for two processes to communicate with each other
- strategy: parent creates pipe, then forks child, which execs new program
- both parent and child share the pipe so both can use it to communicate!
- before the exec of the new program, however, the child may wish to do some
housekeeping of file descriptors -- this will be made clear in the reading