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