home *** CD-ROM | disk | FTP | other *** search
/ GEMini Atari / GEMini_Atari_CD-ROM_Walnut_Creek_December_1993.iso / zip / gnu / gawk213s.lzh / GAWK213S / POPEN.C < prev    next >
C/C++ Source or Header  |  1993-07-29  |  2KB  |  91 lines

  1. #include <stdio.h>
  2. #include "popen.h"
  3. #include <io.h>
  4. #include <string.h>
  5. #include <process.h>
  6.  
  7. static char template[] = "piXXXXXX";
  8. typedef enum { unopened = 0, reading, writing } pipemode;
  9. static
  10. struct {
  11.     char *command;
  12.     char *name;
  13.     pipemode pmode;
  14. } pipes[_NFILE];
  15.  
  16. FILE *
  17. popen( char *command, char *mode ) {
  18.     FILE *current;
  19.     char *name;
  20.     int cur;
  21.     pipemode curmode;
  22.     /*
  23.     ** decide on mode.
  24.     */
  25.     if(strcmp(mode,"r") == 0)
  26.         curmode = reading;
  27.     else if(strcmp(mode,"w") == 0)
  28.         curmode = writing;
  29.     else
  30.         return NULL;
  31.     /*
  32.     ** get a name to use.
  33.     */
  34.     if((name = tempnam(".","pip"))==NULL)
  35.         return NULL;
  36.     /*
  37.     ** If we're reading, just call system to get a file filled with
  38.     ** output.
  39.     */
  40.     if(curmode == reading) {
  41.         char cmd[256];
  42.         sprintf(cmd,"%s > %s",command,name);
  43.         system(cmd);
  44.         if((current = fopen(name,"r")) == NULL)
  45.             return NULL;
  46.     } else {
  47.         if((current = fopen(name,"w")) == NULL)
  48.             return NULL;
  49.     }
  50.     cur = fileno(current);
  51.     pipes[cur].name = name;
  52.     pipes[cur].pmode = curmode;
  53.     pipes[cur].command = strdup(command);
  54.     return current;
  55. }
  56.  
  57. int
  58. pclose( FILE * current) {
  59.     int cur = fileno(current),rval;
  60.     /*
  61.     ** check for an open file.
  62.     */
  63.     if(pipes[cur].pmode == unopened)
  64.         return -1;
  65.     if(pipes[cur].pmode == reading) {
  66.         /*
  67.         ** input pipes are just files we're done with.
  68.         */
  69.         rval = fclose(current);
  70.         unlink(pipes[cur].name);
  71.     } else {
  72.         /*
  73.         ** output pipes are temporary files we have
  74.         ** to cram down the throats of programs.
  75.         */
  76.         char command[256];
  77.         fclose(current);
  78.         sprintf(command,"%s < %s",pipes[cur].command,pipes[cur].name);
  79.         rval = system(command);
  80.         unlink(pipes[cur].name);
  81.     }
  82.     /*
  83.     ** clean up current pipe.
  84.     */
  85.     pipes[cur].pmode = unopened;
  86.     free(pipes[cur].name);
  87.     free(pipes[cur].command);
  88.     return rval;
  89. }
  90.  
  91.