home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / cproto.zip / cproto46 / porting / popen.c < prev    next >
C/C++ Source or Header  |  1998-01-07  |  2KB  |  82 lines

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