Go to the documentation of this file.00001 #include <unistd.h>
00002 #include <stdio.h>
00003 #include <signal.h>
00004 #include <stdlib.h>
00005 #include <sys/types.h>
00006
00007
00008 #ifdef __MINGW32__
00009 # include <io.h>
00010 # include <fcntl.h>
00011 # include <process.h>
00012 #else
00013 # include <sys/wait.h>
00014 # define tst(a,b) (*mode == 'r'? (b) : (a))
00015 #endif
00016
00017 #include <grass/gis.h>
00018
00019
00020 #define READ 0
00021 #define WRITE 1
00022
00023 static int popen_pid[50];
00024
00025
00026 FILE *G_popen(const char *cmd, const char *mode)
00027 {
00028
00029 #ifdef __MINGW32__
00030
00031 int thepipes[2];
00032 FILE *rv = NULL;
00033
00034 fflush(stdout);
00035 fflush(stderr);
00036
00037
00038
00039 if (_pipe(thepipes, 256, O_BINARY) != -1) {
00040 execl("cmd", "cmd", "/c", cmd, (char *)NULL);
00041 close(thepipes[WRITE]);
00042 rv = fdopen(thepipes[READ], mode);
00043 }
00044
00045 return (rv);
00046
00047 #else
00048
00049 int p[2];
00050 int me, you, pid;
00051
00052 fflush(stdout);
00053 fflush(stderr);
00054
00055 if (pipe(p) < 0)
00056 return NULL;
00057 me = tst(p[WRITE], p[READ]);
00058 you = tst(p[READ], p[WRITE]);
00059 if ((pid = fork()) == 0) {
00060
00061 close(me);
00062 close(tst(0, 1));
00063 dup(you);
00064 close(you);
00065 execl("/bin/sh", "sh", "-c", cmd, (char *)NULL);
00066 _exit(1);
00067 }
00068
00069 if (pid == -1)
00070 return NULL;
00071 popen_pid[me] = pid;
00072 close(you);
00073
00074 return (fdopen(me, mode));
00075
00076 #endif
00077
00078 }
00079
00080 int G_pclose(FILE * ptr)
00081 {
00082 RETSIGTYPE(*sigint) ();
00083 #ifdef SIGHUP
00084 RETSIGTYPE(*sighup) ();
00085 #endif
00086 #ifdef SIGQUIT
00087 RETSIGTYPE(*sigquit) ();
00088 #endif
00089 int f;
00090
00091 #ifndef __MINGW32__
00092 int r;
00093 #endif
00094 int status;
00095
00096 f = fileno(ptr);
00097 fclose(ptr);
00098
00099 sigint = signal(SIGINT, SIG_IGN);
00100 #ifdef __MINGW32__
00101 _cwait(&status, popen_pid[f], WAIT_CHILD);
00102 if (0 & status) {
00103 status = -1;
00104 }
00105 #else
00106
00107 #ifdef SIGQUIT
00108 sigquit = signal(SIGQUIT, SIG_IGN);
00109 #endif
00110 #ifdef SIGHUP
00111 sighup = signal(SIGHUP, SIG_IGN);
00112 #endif
00113 while ((r = wait(&status)) != popen_pid[f] && r != -1) ;
00114 if (r == -1)
00115 status = -1;
00116
00117 #endif
00118
00119 signal(SIGINT, sigint);
00120
00121 #ifdef SIGQUIT
00122 signal(SIGQUIT, sigquit);
00123 #endif
00124 #ifdef SIGHUP
00125 signal(SIGHUP, sighup);
00126 #endif
00127
00128 return (status);
00129 }