next up previous Back to Operating Systems Home Page
Next: Assig2: Closing pipes... Up: 1997 term messages Previous: File descriptors across fork(2)/exec(2)

Forking, duping, piping, waiting example

Hi, everyone.

Here is an example of replacing the stdout of a parent with one end of
a pipe, and the stdin of the child with the other end of a pipe.

The parent takes each character and adds one to it (A==>B,  M==>N,
etc).  The child takes each character and subtracts (B==>A, N==>M,
etc).  The net effect is a pass-through filter.

#include <stdio.h>
#include <stdlib.h>

void main()
{
  int filedes[2]; /* pipe */
  int file_rd=fileno(stdin);  /* filedescriptor = 0 */
  int file_wr=fileno(stdout); /* filedescriptor = 1 */

  int ch;

  int pipe_rd;
  int pipe_wr;

  pipe(filedes);

  pipe_wr = filedes[1];
  pipe_rd = filedes[0];

  /* */

  if (fork())
    {
      /* child */
      /* stdin replaced by pipe output */
      dup2(pipe_rd,file_rd);

      close(pipe_wr); /* close part of pipe unneeded */

      while ((ch=fgetc(stdin))>0)
        {
          /* fprintf(stderr, "c=%c\n",ch); */
          fprintf(stdout, "%c",ch-1);
        }

      fprintf(stderr, "child: the last was %d\n",ch);

      close(pipe_rd);
      /* close(file_rd); */
      /* close(file_wr); */
  }
  else
  {
      /* parent */
      /* stdout replaced by pipe input */
      dup2(pipe_wr,file_wr);

      close(pipe_rd); /* close part of pipe unneeded */

      while ((ch=fgetc(stdin))>0)
        {
          fprintf(stdout, "%c",ch+1);
        }

      fprintf(stderr, "parent: the last was %d\n",ch);

      close(pipe_wr);
      /* close(file_rd); */
      /* close(file_wr); */
  }
}


\ Franco Callari