popen.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <signal.h>
  4. #include <stdlib.h>
  5. #include <sys/types.h>
  6. #ifdef __MINGW32__
  7. # include <io.h>
  8. # include <fcntl.h>
  9. # include <process.h>
  10. #else
  11. # include <sys/wait.h>
  12. # define tst(a,b) (*mode == 'r'? (b) : (a))
  13. #endif
  14. #include <grass/gis.h>
  15. #define READ 0
  16. #define WRITE 1
  17. static int popen_pid[50];
  18. FILE *G_popen(const char *cmd, const char *mode)
  19. {
  20. #ifdef __MINGW32__
  21. int thepipes[2];
  22. FILE *rv = NULL;
  23. fflush(stdout);
  24. fflush(stderr);
  25. /*setvbuf ( stdout, NULL, _IONBF, 0 ); */
  26. if (_pipe(thepipes, 256, O_BINARY) != -1) {
  27. execl("cmd", "cmd", "/c", cmd, (char *)NULL);
  28. close(thepipes[WRITE]);
  29. rv = fdopen(thepipes[READ], mode);
  30. }
  31. return (rv);
  32. #else /* __MINGW32__ */
  33. int p[2];
  34. int me, you, pid;
  35. fflush(stdout);
  36. fflush(stderr);
  37. if (pipe(p) < 0)
  38. return NULL;
  39. me = tst(p[WRITE], p[READ]);
  40. you = tst(p[READ], p[WRITE]);
  41. if ((pid = fork()) == 0) {
  42. /* me and you reverse roles in child */
  43. close(me);
  44. close(tst(0, 1));
  45. dup(you);
  46. close(you);
  47. execl("/bin/sh", "sh", "-c", cmd, (char *)NULL);
  48. _exit(1);
  49. }
  50. if (pid == -1)
  51. return NULL;
  52. popen_pid[me] = pid;
  53. close(you);
  54. return (fdopen(me, mode));
  55. #endif /* __MINGW32__ */
  56. }
  57. int G_pclose(FILE * ptr)
  58. {
  59. RETSIGTYPE(*sigint) ();
  60. #ifdef SIGHUP
  61. RETSIGTYPE(*sighup) ();
  62. #endif
  63. #ifdef SIGQUIT
  64. RETSIGTYPE(*sigquit) ();
  65. #endif
  66. int f;
  67. #ifndef __MINGW32__
  68. int r;
  69. #endif
  70. int status;
  71. f = fileno(ptr);
  72. fclose(ptr);
  73. sigint = signal(SIGINT, SIG_IGN);
  74. #ifdef __MINGW32__
  75. _cwait(&status, popen_pid[f], WAIT_CHILD);
  76. if (0 & status) {
  77. status = -1;
  78. }
  79. #else
  80. #ifdef SIGQUIT
  81. sigquit = signal(SIGQUIT, SIG_IGN);
  82. #endif
  83. #ifdef SIGHUP
  84. sighup = signal(SIGHUP, SIG_IGN);
  85. #endif
  86. while ((r = wait(&status)) != popen_pid[f] && r != -1) ;
  87. if (r == -1)
  88. status = -1;
  89. #endif /* __MINGW32__ */
  90. signal(SIGINT, sigint);
  91. #ifdef SIGQUIT
  92. signal(SIGQUIT, sigquit);
  93. #endif
  94. #ifdef SIGHUP
  95. signal(SIGHUP, sighup);
  96. #endif
  97. return (status);
  98. }