home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / misc / volume28 / cproto / part02 / popen.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-03-15  |  1.5 KB  |  78 lines

  1. /* $Id: popen.c 3.2 92/03/14 11:58:07 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 M_I86
  38.     sprintf(opt, "-o%s.", pipe_name);
  39. #else
  40.     sprintf(opt, "-o%s", pipe_name);
  41. #endif
  42.     *arg++ = opt;
  43.     while ((s = strtok(NULL, " ")) != NULL) {
  44.     *arg++ = s;
  45.     }
  46.     *arg = NULL;
  47.  
  48.     /* Redirect the program's stdout to /dev/null. */
  49.     ostdout = dup(fileno(stdout));
  50.     freopen("nul", "w", stdout);
  51.  
  52.     /* Run the program. */
  53.     status = spawnvp(P_WAIT, argv[0], argv);
  54.  
  55.     /* Restore stdout. */
  56.     dup2(ostdout, fileno(stdout));
  57.     free(cmdline);
  58.  
  59.     if (status != 0)
  60.     return NULL;
  61.  
  62.     /* Open the intermediate file and return the stream. */
  63.     return fopen(pipe_name, type) ;
  64. }
  65.  
  66. /* Close the pipe.
  67.  */
  68. int
  69. pclose (f)
  70. FILE *f;
  71. {
  72.     int status;
  73.  
  74.     status = fclose(f);
  75.     unlink(pipe_name);
  76.     return status;
  77. }
  78.