summaryrefslogtreecommitdiff
path: root/reference/C/CONTRIB/OR_USING_C/09.4.c
blob: dba1cd6872c667c4975ab31bb8b759a0f34f7243 (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
 * mailer - open a pipe to the mail command and send the user
 *          mail.
 */
#include <stdio.h>

main()
{
    FILE *fp;
    int pid, pipefds[2];
    char *username, *getlogin();

    /*
     * Get the user's name.
     */
    if ((username = getlogin()) == NULL) {
        fprintf(stderr, "Who are you?\n");
        exit(1);
    }

    /*
     * Create the pipe.  This has to be done
     * BEFORE the fork.
     */
    if (pipe(pipefds) < 0) {
        perror("pipe");
        exit(1);
    }

    if ((pid = fork()) < 0) {
        perror("fork");
        exit(1);
    }

    /*
     * The child process executes the stuff inside
     * the if.
     */
    if (pid == 0) {
        /*
         * Make the read side of the pipe our
         * standard input.
         */
        close(0);
        dup(pipefds[0]);
        close(pipefds[0]);

        /*
         * Close the write side of the pipe;
         * we'll let our output go to the screen.
         */
        close(pipefds[1]);

        /*
         * Execute the command "mail username".
         */
        execl("/bin/mail", "mail", username, 0);
        perror("exec");
        exit(1);
    }

    /*
     * The parent executes this code.
     */

    /*
     * Close the read side of the pipe; we
     * don't need it (and the child is not
     * writing on the pipe anyway).
     */
    close(pipefds[0]);

    /*
     * Convert the write side of the pipe to stdio.
     */
    fp = fdopen(pipefds[1], "w");

    /*
     * Send a message, close the pipe.
     */
    fprintf(fp, "Hello from your program.\n");
    fclose(fp);

    /*
     * Wait for the process to terminate.
     */     
    while (wait((int *) 0) != pid)
        ;

    exit(0);
}