home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 5 / Skunkware 5.iso / src / Tools / cproto-3.0 / popen.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-05-03  |  1.5 KB  |  80 lines

  1. /* $Id: popen.c 3.3 1992/06/10 20:56:30 cthuang Exp $
  2.  *
  3.  * Imitate a UNIX pipe in MS-DOS.
  4.  */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <process.h>
  8. #include <io.h>
  9. #include "cproto.h"
  10.  
  11. static char pipe_name[FILENAME_MAX];    /* name of the temporary file */
  12.  
  13. /* Open a pipe for reading.
  14.  */
  15. FILE *
  16. popen (cmd, type)
  17. char *cmd, *type;
  18. {
  19.     char *tmpdir, *argv[30], **arg, *cmdline, *s, opt[FILENAME_MAX];
  20.     int ostdout, status;
  21.  
  22.     /* Set temporary file name. */
  23.     if ((tmpdir = getenv("TMP")) == NULL) {
  24.     pipe_name[0] = '\0';
  25.     } else {
  26.     strcpy(pipe_name, tmpdir);
  27.     trim_path_sep(pipe_name);
  28.     strcat(pipe_name, "/");
  29.     }
  30.     strcat(pipe_name, tmpnam(NULL));
  31.  
  32.     /* Split the command into an argument array. */
  33.     cmdline = xstrdup(cmd);
  34.     arg = argv;
  35.     s = strtok(cmdline, " ");
  36.     *arg++ = s;
  37. #ifdef TURBO_CPP
  38.     sprintf(opt, "-o%s", pipe_name);
  39.     *arg++ = opt;
  40. #endif
  41.     while ((s = strtok(NULL, " ")) != NULL) {
  42.     *arg++ = s;
  43.     }
  44.     *arg = NULL;
  45.  
  46.     /* Redirect the program's stdout. */
  47.     ostdout = dup(fileno(stdout));
  48. #ifdef TURBO_CPP
  49.     freopen("nul", "w", stdout);
  50. #else
  51.     freopen(pipe_name, "w", stdout);
  52. #endif
  53.  
  54.     /* Run the program. */
  55.     status = spawnvp(P_WAIT, argv[0], argv);
  56.  
  57.     /* Restore stdout. */
  58.     dup2(ostdout, fileno(stdout));
  59.     free(cmdline);
  60.  
  61.     if (status != 0)
  62.     return NULL;
  63.  
  64.     /* Open the intermediate file and return the stream. */
  65.     return fopen(pipe_name, type) ;
  66. }
  67.  
  68. /* Close the pipe.
  69.  */
  70. int
  71. pclose (f)
  72. FILE *f;
  73. {
  74.     int status;
  75.  
  76.     status = fclose(f);
  77.     unlink(pipe_name);
  78.     return status;
  79. }
  80.