Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 15.2 Pipes 537



  1. If wewriteto a pipe whose read end has been closed, the signalSIGPIPEis
    generated. If we either ignorethe signal or catch it and return from the signal
    handler,writereturns−1witherrnoset toEPIPE.


When we’rewriting to a pipe (or FIFO), the constant PIPE_BUFspecifies the
kernel’s pipe buffer size. AwriteofPIPE_BUFbytes or less will not be interleaved
with thewritesfromother processes to the same pipe (or FIFO). But if multiple
processes arewriting to a pipe (or FIFO), and if wewritemorethanPIPE_BUFbytes,
the data might be interleaved with the data from the other writers.We can determine
the value ofPIPE_BUFby usingpathconforfpathconf(recall Figure2.12).

Example


Figure15.5 shows the code to create a pipe between a parent and its child and to send
data down the pipe.
#include "apue.h"
int
main(void)
{
int n;
int fd[2];
pid_t pid;
char line[MAXLINE];
if (pipe(fd) < 0)
err_sys("pipe error");
if ((pid = fork()) < 0) {
err_sys("fork error");
}else if (pid > 0) { /* parent */
close(fd[0]);
write(fd[1], "hello world\n", 12);
}else { /* child */
close(fd[1]);
n=read(fd[0], line, MAXLINE);
write(STDOUT_FILENO, line, n);
}
exit(0);
}

Figure 15.5 Send data from parent to child over a pipe

Note that the pipe direction herematches the orientation shown in Figure15.4.

In the previous example, we called read and write directly on the pipe
descriptors. What is moreinteresting is to duplicate the pipe descriptors onto standard
input or standardoutput. Often, the child then runs some other program, and that
program can either read from its standardinput (the pipe that we created) or write to its
standardoutput (the pipe).
Free download pdf