(root)/
gcc-13.2.0/
gcc/
testsuite/
gcc.dg/
analyzer/
pipe-glibc.c
       1  /* Example of pipe usage from glibc manual.  */
       2  
       3  #include <sys/types.h>
       4  #include <unistd.h>
       5  #include <stdio.h>
       6  #include <stdlib.h>
       7  
       8  /* Read characters from the pipe and echo them to stdout. */
       9  
      10  void
      11  read_from_pipe (int file)
      12  {
      13    FILE *stream;
      14    int c;
      15    stream = fdopen (file, "r");
      16    if (stream == NULL)
      17      exit (EXIT_FAILURE);
      18    while ((c = fgetc (stream)) != EOF)
      19      putchar (c);
      20    fclose (stream);
      21  }
      22  
      23  /* Write some random text to the pipe. */
      24  
      25  void
      26  write_to_pipe (int file)
      27  {
      28    FILE *stream;
      29    stream = fdopen (file, "w");
      30    if (stream == NULL)
      31      exit (EXIT_FAILURE);
      32    fprintf (stream, "hello, world!\n");
      33    fprintf (stream, "goodbye, world!\n");
      34    fclose (stream);
      35  }
      36  
      37  int
      38  main (void)
      39  {
      40    pid_t pid;
      41    int mypipe[2];
      42  
      43    /* Create the pipe. */
      44    if (pipe (mypipe))
      45      {
      46        fprintf (stderr, "Pipe failed.\n");
      47        return EXIT_FAILURE;
      48      }
      49  
      50  
      51    /* Create the child process. */
      52    pid = fork ();
      53    if (pid == (pid_t) 0)
      54      {
      55        /* This is the child process.
      56           Close other end first. */
      57        close (mypipe[1]);
      58        read_from_pipe (mypipe[0]);
      59        return EXIT_SUCCESS;
      60      }
      61    else if (pid < (pid_t) 0)
      62      {
      63        /* The fork failed. */
      64        fprintf (stderr, "Fork failed.\n");
      65        return EXIT_FAILURE;
      66      }
      67    else
      68      {
      69        /* This is the parent process.
      70           Close other end first. */
      71        close (mypipe[0]);
      72        write_to_pipe (mypipe[1]);
      73        return EXIT_SUCCESS;
      74      }
      75  }