| 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 <stdio.h> |
| 8 |
#include <sys/types.h> |
| 9 |
#include <sys/wait.h> |
| 10 |
#include <unistd.h> |
| 11 |
|
| 12 |
int main () |
| 13 |
{ |
| 14 |
int fds[2]; |
| 15 |
pid_t pid; |
| 16 |
|
| 17 |
/* Create a pipe. File descriptors for the two ends of the pipe are |
| 18 |
placed in fds. */ |
| 19 |
pipe (fds); |
| 20 |
/* Fork a child process. */ |
| 21 |
pid = fork (); |
| 22 |
if (pid == (pid_t) 0) { |
| 23 |
/* This is the child process. Close our copy of the write end of |
| 24 |
the file descriptor. */ |
| 25 |
close (fds[1]); |
| 26 |
/* Connect the read end of the pipe to standard input. */ |
| 27 |
dup2 (fds[0], STDIN_FILENO); |
| 28 |
/* Replace the child process with the "sort" program. */ |
| 29 |
execlp ("sort", "sort", 0); |
| 30 |
} |
| 31 |
else { |
| 32 |
/* This is the parent process. */ |
| 33 |
FILE* stream; |
| 34 |
/* Close our copy of the read end of the file descriptor. */ |
| 35 |
close (fds[0]); |
| 36 |
/* Convert the write file descriptor to a FILE object, and write |
| 37 |
to it. */ |
| 38 |
stream = fdopen (fds[1], "w"); |
| 39 |
fprintf (stream, "This is a test.\n"); |
| 40 |
fprintf (stream, "Hello, world.\n"); |
| 41 |
fprintf (stream, "My dog has fleas.\n"); |
| 42 |
fprintf (stream, "This program is great.\n"); |
| 43 |
fprintf (stream, "One fish, two fish.\n"); |
| 44 |
fflush (stream); |
| 45 |
close (fds[1]); |
| 46 |
/* Wait for the child process to finish. */ |
| 47 |
waitpid (pid, NULL, 0); |
| 48 |
} |
| 49 |
|
| 50 |
return 0; |
| 51 |
} |