Lab 13 Preparation

To prepare for Lab 13 on the pipe() and dup() function calls and the corresponding O/S services, first review the lecture notes for Redirection and Real Pipes. Make copies of the source files for all the sample programs in redir and pipe (they will all be found in the directories in ~allisor/Student/ in the Linux Lab) and compile them, then run each.

Read over the source code carefully and check the output from your test runs until you understand why each one behaves as it does. Modify some or all of the samples to see how the behaviour changes as you re-compile and re-run each.

In Stevens/Rago you will find information and examples about dup() and dup2() in Section 3.12, but you should also read most of sections 3.1 to 3.11 as well to review Unix I/O. The pipe() function is in Section 15.2. The Introduction in Section 15.1 may be of some interest, but you will not need (or use) the popen() and pclose() functions of Section 15.3 this semester.

Finally, you can use parts of your programs from previous lab exercises as the basis for Lab 13, but you should copy the source files and Makefile into a new subdirectory.

pipe(2)

#include <unistd.h>

int pipe(int filedes[2]);

pipe() creates a pair of I/O descriptors and places them in the array pointed to by filedes. Elements of the integer array are used as file descriptors, filedes[0] for reading and filedes[1] for writing.

On success, 0 is returned. On error, -1 is returned, and errno is set.

When a pipe has been opened in the parent and passed on to a child process, the unused file descriptor at each end must be closed for I/O and end-of-file to work correctly.

dup(2) and dup2(2)

#include <unistd.h>

int dup(int oldfd);

int dup2(int oldfd, int newfd);

dup() and dup2() create a copy of the file descriptor oldfd. After successful return from either duplication function, the old and new descriptors may be used interchangeably.

dup() and dup2() return the new descriptor, or -1 if an error occurred (in which case, errno is set appropriately).

Once a file descriptor has been duplicated, oldfd should be closed unless it is also going to be used.

That is, the following is correct usage to redirect file to stdout:

fd = open(file, O_WRONLY | O_TRUNC | O_CREAT, 0600);

dup2(fd, fileno(stdout));

close(fd);