   1  /* Listing 1
   2   * popen() 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_popen(slines, sbuf, com_str);
  17  fprintf(stderr,"count is %d\n", count);
  18  for(i=0; i<count;	i++)
  19 	 printf("%s\n",	slines[i]);
  20  }
  21  /*
  22   * This function executes	a piped	command	passed as
  23   * a pointer-to-string, exe_str.
  24   * buffer is the	array where each line is stored
  25   * lineptr is an array-of-pointers where each element of the
  26   * array points to the beginning of each line stored in buffer.
  27   *
  28   * returns the number of lines read into buffer, cnt.
  29   */
  30  int run_popen(lineptr, buffer, exe_str)
  31  char *lineptr[]; /*array-of-pointers to addresses */
  32  char buffer[];  /*buffer to save strings */
  33  char *exe_str;   /*pipe command */
  34  {
  35  int i, cnt=0;
  36  FILE *ptr, *popen();
  37  char *bufstart, *bufend, line[MAX_TXT], *fgets();
  38 
  39  bufstart = buffer;	       /*mark start of available space*/
  40  bufend = buffer + MAX_CHARS;    /*mark end of available space*/
  41  if((ptr =	popen(exe_str, "r")) ==	NULL)
  42 	 fatal("Couldn't open pipe");
  43 
  44  for(i=0; i<MAX_LINES; i++)
  45 	 {
  46 	 if(fgets(line,	MAX_TXT, ptr) == NULL)
  47 	    break;
  48 	 line[strlen(line)-1] =	'\0'; /* no new-lines*/
  49 	 if((bufstart +	strlen(line) + 1) >= bufend)
  50 	    fatal("Line	too long");
  51 	 lineptr[i]=bufstart;	     /*save the	address	of the line*/
  52 	 strcpy(bufstart,line);	     /*save the	line into buffer*/
  53 	 bufstart += strlen(line)+1; /*update starting pointer*/
  54 	 cnt++;
  55 	 }
  56  fclose(ptr);
  57  return cnt;
  58  }
  59  /*
  60   * Fatal Error
  61   */
  62  int fatal(x)
  63  char *x;
  64  {
  65  perror(x);
  66  exit(1);
  67  }

