pipe -- Create Unnamed Pipe


SYNOPSIS
#include <unistd.h>
int pipe(int fd[2]);
DESCRIPTION
pipe
creates an I/O channel through which a process
communicates with another process or with itself. fd
points to
a memory area where two file descriptors are stored. pipe
stores
the file descriptor for the output end of the pipe in fd[0]
, and
it stores the file descriptor for the input end of the pipe in fd[2]
.
The first data written to the pipe are the first to be read.
O_NONBLOCK
and FD_CLOEXEC
are turned off at both ends of the pipe.
RETURN VALUE
pipe
returns 0 if it is successful, and
- 1 if it is not successful.
EXAMPLE
This example invokes the ls
shell command using fork
and
exec
, and uses a pipe allocated to file descriptor 1 to obtain the
output of ls
and write it to stderr
(which may be a non-HFS
terminal or disk file if the example is run under MVS batch or TSO):
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <lclib.h>
static void do_ls(char * const []);
main()
{
int pipefds[2];
pid_t pid;
char *const parmList[] = {"/bin/ls", "-l", "/u/userid/dirname",
NULL };
char lsout[200]; /* buffer for out ls output */
int amt;
int status; /* status code from ls */
fclose(stdout); /* Avoid stdio interfering with fd 1. */
pipe(pipefds); /* Create both ends of a pipe. */
/* Make write end of pipe fd 1. */
dup2(pipefds[1],STDOUT_FILENO);
/* Close write end. */
if (pipefds[1] != 1) close(pipefds[1]);
/* In child process, invoke ls. */
if ((pid = fork()) == 0) do_ls(parmList);
close(1); /* Close write end of pipe in parent. */
for(;;) { /* Read from the pipe. */
amt = read(pipefds[0], lsout, sizeof(lsout));
if (amt <= 0) break;
fwrite(lsout, 1, amt, stderr); /*Write ls output to stderr.*/
}
wait(&status); /* Wait for ls to complete. */
close(pipefds[0]); /* Close pipe input end. */
if (WIFEXITED(status)) exit(WEXITSTATUS(status));
else /* If ls failed, use kill to fail the same way. */
kill(0, WTERMSIG(status));
}
static void do_ls(char *const parmList[]) {
int rc;
rc = execvp("ls", parmList); /* Pass control to ls. */
/* execvp must have failed! */
perror("execvp failure");
abort(); /* Terminate process the hard way. */
}
RELATED FUNCTIONS
mkfifo
SEE ALSO