File: popen.c

package info (click to toggle)
grass 6.0.2-6
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 40,044 kB
  • ctags: 31,303
  • sloc: ansic: 321,125; tcl: 25,676; sh: 11,176; cpp: 10,098; makefile: 5,025; fortran: 1,846; yacc: 493; lex: 462; perl: 133; sed: 1
file content (125 lines) | stat: -rw-r--r-- 2,059 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>

#ifdef __MINGW32__
#  include <io.h>
#  include <fcntl.h>
#  include <process.h>
#else
#  include <sys/wait.h>
#  define tst(a,b)        (*mode == 'r'? (b) : (a))
#endif

#include "gis.h"

#define READ      0
#define WRITE     1

static  int     popen_pid[50];

FILE *G_popen(
    char    *cmd,
    char    *mode)
{

#ifdef __MINGW32__

    int thepipes[2];
    FILE *rv = NULL;

    fflush (stdout);
    fflush (stderr);

    /*setvbuf ( stdout, NULL, _IONBF, 0 );*/

    if ( _pipe ( thepipes, 256, O_BINARY ) != -1 ) {
        execl ( "cmd", "cmd", "/c", cmd, 0 );
	close ( thepipes[WRITE] );
	rv = fdopen ( thepipes[READ], mode ); 
    }

    return ( rv );

#else /* __MINGW32__ */

    int p[2];
    int me, you, pid;

    fflush (stdout);
    fflush (stderr);

    if(pipe(p) < 0)
        return NULL;
    me = tst(p[WRITE], p[READ]);
    you = tst(p[READ], p[WRITE]);
    if((pid = fork()) == 0)
    {
/* me and you reverse roles in child */
	close(me);
	close(tst(0, 1));
	dup(you);
	close(you);
	execl("/bin/sh", "sh", "-c", cmd, 0);
	_exit(1);
    }

    if(pid == -1)
	return NULL;
    popen_pid[me] = pid;
    close(you);

    return(fdopen(me, mode));

#endif /* __MINGW32__ */

}

int G_pclose( FILE *ptr)
{
    void (*sigint)();
#ifdef SIGHUP    
    void (*sighup)();
#endif
#ifdef SIGQUIT
    void (*sigquit)();
#endif
    int f, r;
    int status;

    f = fileno(ptr);
    fclose(ptr);

    sigint  = signal(SIGINT, SIG_IGN);
#ifdef __MINGW32__
    _cwait ( &status, popen_pid[f], WAIT_CHILD );
    if ( 0 & status ) {
      status = -1;
    }
#else

#ifdef SIGQUIT
    sigquit = signal(SIGQUIT, SIG_IGN);
#endif
#ifdef SIGHUP    
    sighup  = signal(SIGHUP, SIG_IGN);
#endif
    while((r = wait(&status)) != popen_pid[f] && r != -1)
	    ;
    if(r == -1)
	status = -1;

#endif /* __MINGW32__ */

    signal(SIGINT, sigint);

#ifdef SIGQUIT
    signal(SIGQUIT, sigquit);
#endif
#ifdef SIGHUP    
    signal(SIGHUP, sighup);
#endif

    return(status);
}