Back to index

glibc  2.9
pipe.c
Go to the documentation of this file.
00001 #include <sys/types.h>
00002 #include <unistd.h>
00003 #include <stdio.h>
00004 #include <stdlib.h>
00005 
00006 /* Read characters from the pipe and echo them to @code{stdout}.  */
00007 
00008 void
00009 read_from_pipe (int file)
00010 {
00011   FILE *stream;
00012   int c;
00013   stream = fdopen (file, "r");
00014   while ((c = fgetc (stream)) != EOF)
00015     putchar (c);
00016   fclose (stream);
00017 }
00018 
00019 /* Write some random text to the pipe. */
00020 
00021 void
00022 write_to_pipe (int file)
00023 {
00024   FILE *stream;
00025   stream = fdopen (file, "w");
00026   fprintf (stream, "hello, world!\n");
00027   fprintf (stream, "goodbye, world!\n");
00028   fclose (stream);
00029 }
00030 
00031 int
00032 main (void)
00033 {
00034   pid_t pid;
00035   int mypipe[2];
00036 
00037 /*@group*/
00038   /* Create the pipe.  */
00039   if (pipe (mypipe))
00040     {
00041       fprintf (stderr, "Pipe failed.\n");
00042       return EXIT_FAILURE;
00043     }
00044 /*@end group*/
00045 
00046   /* Create the child process.  */
00047   pid = fork ();
00048   if (pid == (pid_t) 0)
00049     {
00050       /* This is the child process.
00051         Close other end first.  */
00052       close (mypipe[1]);
00053       read_from_pipe (mypipe[0]);
00054       return EXIT_SUCCESS;
00055     }
00056   else if (pid < (pid_t) 0)
00057     {
00058       /* The fork failed.  */
00059       fprintf (stderr, "Fork failed.\n");
00060       return EXIT_FAILURE;
00061     }
00062   else
00063     {
00064       /* This is the parent process.
00065         Close other end first.  */
00066       close (mypipe[0]);
00067       write_to_pipe (mypipe[1]);
00068       return EXIT_SUCCESS;
00069     }
00070 }