Debian Codegraph @

listings/chapter-5/pipe.c

raw
1 /***********************************************************************
2 * Code listing from "Advanced Linux Programming," by CodeSourcery LLC *
3 * Copyright (C) 2001 by New Riders Publishing *
4 * See COPYRIGHT for license information. *
5 ***********************************************************************/
6
7 #include <stdlib.h>
8 #include <stdio.h>
9 #include <unistd.h>
10
11 /* Write COUNT copies of MESSAGE to STREAM, pausing for a second
12 between each. */
13
14 void writer (const char* message, int count, FILE* stream)
15 {
16 for (; count > 0; --count) {
17 /* Write the message to the stream, and send it off immediately. */
18 fprintf (stream, "%s\n", message);
19 fflush (stream);
20 /* Snooze a while. */
21 sleep (1);
22 }
23 }
24
25 /* Read random strings from the stream as long as possible. */
26
27 void reader (FILE* stream)
28 {
29 char buffer[1024];
30 /* Read until we hit the end of the stream. fgets reads until
31 either a newline or the end-of-file. */
32 while (!feof (stream)
33 && !ferror (stream)
34 && fgets (buffer, sizeof (buffer), stream) != NULL)
35 fputs (buffer, stdout);
36 }
37
38 int main ()
39 {
40 int fds[2];
41 pid_t pid;
42
43 /* Create a pipe. File descriptors for the two ends of the pipe are
44 placed in fds. */
45 pipe (fds);
46 /* Fork a child process. */
47 pid = fork ();
48 if (pid == (pid_t) 0) {
49 FILE* stream;
50 /* This is the child process. Close our copy of the write end of
51 the file descriptor. */
52 close (fds[1]);
53 /* Convert the read file descriptor to a FILE object, and read
54 from it. */
55 stream = fdopen (fds[0], "r");
56 reader (stream);
57 close (fds[0]);
58 }
59 else {
60 /* This is the parent process. */
61 FILE* stream;
62 /* Close our copy of the read end of the file descriptor. */
63 close (fds[0]);
64 /* Convert the write file descriptor to a FILE object, and write
65 to it. */
66 stream = fdopen (fds[1], "w");
67 writer ("Hello, world.", 5, stream);
68 close (fds[1]);
69 }
70
71 return 0;
72 }