1PIPE(2) Linux Programmer's Manual PIPE(2)
2
3
4
6 pipe - create pipe
7
9 #include <unistd.h>
10
11 int pipe(int filedes[2]);
12
14 pipe() creates a pair of file descriptors, pointing to a pipe inode,
15 and places them in the array pointed to by filedes. filedes[0] is for
16 reading, filedes[1] is for writing.
17
19 On success, zero is returned. On error, -1 is returned, and errno is
20 set appropriately.
21
23 EFAULT filedes is not valid.
24
25 EMFILE Too many file descriptors are in use by the process.
26
27 ENFILE The system limit on the total number of open files has been
28 reached.
29
31 POSIX.1-2001.
32
34 The following program creates a pipe, and then fork(2)s to create a
35 child process. After the fork(2), each process closes the descriptors
36 that it doesn't need for the pipe (see pipe(7)). The parent then
37 writes the string contained in the program's command-line argument to
38 the pipe, and the child reads this string a byte at a time from the
39 pipe and echoes it on standard output.
40
41 #include <sys/wait.h>
42 #include <assert.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <unistd.h>
46 #include <string.h>
47
48 int
49 main(int argc, char *argv[])
50 {
51 int pfd[2];
52 pid_t cpid;
53 char buf;
54
55 assert(argc == 2);
56
57 if (pipe(pfd) == -1) { perror("pipe"); exit(EXIT_FAILURE); }
58
59 cpid = fork();
60 if (cpid == -1) { perror("fork"); exit(EXIT_FAILURE); }
61
62 if (cpid == 0) { /* Child reads from pipe */
63 close(pfd[1]); /* Close unused write end */
64
65 while (read(pfd[0], &buf, 1) > 0)
66 write(STDOUT_FILENO, &buf, 1);
67
68 write(STDOUT_FILENO, "\n", 1);
69 close(pfd[0]);
70 _exit(EXIT_SUCCESS);
71
72 } else { /* Parent writes argv[1] to pipe */
73 close(pfd[0]); /* Close unused read end */
74 write(pfd[1], argv[1], strlen(argv[1]));
75 close(pfd[1]); /* Reader will see EOF */
76 wait(NULL); /* Wait for child */
77 exit(EXIT_SUCCESS);
78 }
79 }
80
81
83 fork(2), read(2), socketpair(2), write(2), popen(3), pipe(7)
84
85
86
87Linux 2.6.7 2004-06-17 PIPE(2)