   1  /* Listing 2
   2   * read pipe() example
   3   */
   4  #include <stdio.h>
   5  #define MAX_LINES	99
   6  #define MAX_CHARS	4000
   7  #define MAX_TXT 256
   8 
   9  main()
  10  {
  11  char *slines[MAX_LINES];
  12  char sbuf[MAX_CHARS];
  13  char *com_str="who|sort|pr -n -t|grep -v '^[ \\t]*$'";
  14  int count,i;
  15 
  16  count=run_rpipe(slines, sbuf, com_str);
  17  printf("count is %d\n", count);
  18  for(i=0; i<count;	i++)
  19 	 printf("%s\n",	slines[i]);
  20  }
  21  /*
  22  *	This function:
  23  *	1) creates a pipe with pipe().
  24  *	2) creates another process with	fork().
  25  *	3) couples standard output to the writing end of	the pipe
  26  *	   using the dup() call.
  27  *	4) closes file descriptors.
  28  *	5) executes the	child process.
  29  *	6) closes the write side of the pipe.
  30  *	7) opens the read side of the pipe using fdopen().
  31  *	8) reads to the	end of the pipe.
  32  *	9) closes the file pointer.
  33  *
  34  *	buffer is the array where each line is stored.
  35  *	lineptr	is an array-of-pointers	where each element of the
  36  *	array points to	the beginning of each line stored in buffer.
  37  *
  38  *	returns	the number of lines read into buffer, cnt.
  39  */
  40  int run_rpipe(lineptr, buffer, exe_str)
  41  char *lineptr[]; /*array-of-pointers to store addresses */
  42  char buffer[];   /*buffer to store strings */
  43  char *exe_str;   /*pipe command */
  44  {
  45  int i, p[2], pid,	cnt=0;
  46  FILE *ptr, *fdopen();
  47  char *bufstart, *bufend, line[MAX_TXT], *fgets();
  48 
  49  bufstart = buffer;
  50  bufend = buffer +	MAX_CHARS;
  51 
  52  if(pipe(p) < 0)
  53 	 fatal("pipe call");
  54 
  55  switch(pid=fork())
  56 	 {
  57 	 case -1:
  58 	    fatal("fork	call in	run_rpipe");
  59 	 case 0:
  60 	    close(1);	 /*close the standard output */
  61 	    dup(p[1]);	 /*write side of the pipe*/
  62 	    close(p[0]); /*save	the file descriptors*/
  63 	    close(p[1]);
  64 	    execlp("/bin/sh", "sh", "-c", exe_str, NULL);
  65 	    fatal("exec	call in	run_rpipe");
  66 	  }
  67  close(p[1]);       /*close the write side of the parent*/
  68  if((ptr=fdopen(p[0],"r")), ptr ==	NULL)
  69 	 fatal("fdopen call in run_rpipe");
  70 
  71  for(i = 0; i < MAX_LINES;	i++)
  72 	 {
  73 	 if(fgets(line,	MAX_TXT, ptr) == NULL)
  74 	    break;
  75 	 line[strlen(line)-1] =	'\0';
  76 	 if((bufstart +	strlen(line) + 1) >= bufend)
  77 	    fatal("Line	too long");
  78 	 lineptr[i]=bufstart;
  79 	 strcpy(bufstart,line);
  80 	 bufstart += strlen(line)+1;
  81 	 cnt++;
  82 	 }
  83  fclose(ptr);
  84  /*wait for child process to finish*/
  85  while(wait((int *)0) != pid)
  86 	 ;
  87  return cnt;
  88  }
