blob: ea3c5a6a54343318100d68f21d31f0472c37c4c4 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/* https://www.youtube.com/watch?v=gaXigSu72A4 */
static inline void die(const char* msg) {
perror(msg);
exit(EXIT_FAILURE);
}
int main(int argc, char **argv) {
int pdes[2];
pid_t child;
if (pipe(pdes) < 0)
die("pipe()");
if ((child = fork()) < 0)
die("fork()");
if (child == 0) {
/* child process */
close(pdes[0]);
close(1); /* close stdout */
if (dup(pdes[1]) < 0)
die("dup()");
/* now stdout and pdes[1] are equivalent (dup returns lowest free descriptor) */
if (execlp("cat", "cat", "/etc/passwd", NULL) < 0)
die("execlp()");
exit(EXIT_SUCCESS);
}
else {
/* parent process */
close(0); /* close stdin */
close(pdes[1]);
if (dup(pdes[0]) < 0)
die("dup()");
/* now stdin and pdes[0] are equivalent (dup returns lowest free descriptor) */
if (execlp("wc", "wc", "-l", NULL) < 0)
die("execlp()");
exit(EXIT_SUCCESS);
}
return 0;
}
|