summaryrefslogtreecommitdiffstats
path: root/dup.c
blob: 1d4bc02760f0a250fbbabebd11b273994e28bcbe (plain)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* dup.c
 *
 * Child piping input to parent
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <wait.h>

extern char **environ;

int main(int argc, char **argv)
{
    pid_t pid;
    int stat_loc;

    int pfds[2];
    int ret;

    if (pipe(pfds) == 0)
    {
        pid = fork();
        if (pid == -1)
        {
            perror("fork");
            exit(EXIT_FAILURE);
        }

        if (!pid)
        {
            close(1);         /* break the link to stdout, dup2 already kills this but meh */
            dup2(pfds[1], 1); /* redirect stdout to pfds[1] */
            close(pfds[1]);   /* new stdout has been setup above, pfds[1] can be closed since it's a dup */

            close(pfds[0]);   /* child will not be reading anything from out pipe */

            execlp("ls", "ls", "-1", NULL);
        }
        else
        {
            close(0);         /* break the link to stdin */
            dup2(pfds[0], 0); /* redirect stdin to pfds[0] */
            close(pfds[0]);   /* new stdin has been setup above, pfds[1] can be closed since it's a dup */

            close(pfds[1]);   /* parent will not be writing anything into our pipe */

            ret = waitpid(pid, &stat_loc, WCONTINUED);
            execlp("wc", "wc", "-l", NULL);
        }
    }
    else
    {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    ret = ret; /* hush the dumb compiler */

    close(pfds[0]);
    close(pfds[1]);

    return 0;
}