@@ -74,9 +74,7 @@ static ProcessPair* process_get(FILE *stream)
74
74
TWLS_FETCH ();
75
75
76
76
for (ptr = TWG (process ); ptr < (TWG (process ) + TWG (process_size )); ptr ++ ) {
77
- if (stream != NULL && ptr -> stream == stream ) {
78
- break ;
79
- } else if (stream == NULL && !ptr -> inuse ) {
77
+ if (ptr -> stream == stream ) {
80
78
break ;
81
79
}
82
80
}
@@ -96,6 +94,14 @@ static ProcessPair* process_get(FILE *stream)
96
94
return ptr ;
97
95
}
98
96
97
+ static HANDLE dupHandle (HANDLE fh , BOOL inherit ) {
98
+ HANDLE copy , self = GetCurrentProcess ();
99
+ if (!DuplicateHandle (self , fh , self , & copy , 0 , inherit , DUPLICATE_SAME_ACCESS |DUPLICATE_CLOSE_SOURCE )) {
100
+ return NULL ;
101
+ }
102
+ return copy ;
103
+ }
104
+
99
105
TSRM_API FILE * popen (const char * command , const char * type )
100
106
{
101
107
FILE * stream = NULL ;
@@ -146,17 +152,18 @@ TSRM_API FILE* popen(const char *command, const char *type)
146
152
proc = process_get (NULL );
147
153
148
154
if (read ) {
155
+ in = dupHandle (in , FALSE);
149
156
fno = _open_osfhandle ((long )in , _O_RDONLY | mode );
150
157
CloseHandle (out );
151
158
} else {
159
+ out = dupHandle (out , FALSE);
152
160
fno = _open_osfhandle ((long )out , _O_WRONLY | mode );
153
161
CloseHandle (in );
154
162
}
155
163
156
164
stream = _fdopen (fno , type );
157
165
proc -> prochnd = process .hProcess ;
158
166
proc -> stream = stream ;
159
- proc -> inuse = 1 ;
160
167
return stream ;
161
168
}
162
169
@@ -172,16 +179,12 @@ TSRM_API int pclose(FILE* stream)
172
179
fflush (process -> stream );
173
180
fclose (process -> stream );
174
181
182
+ WaitForSingleObject (process -> prochnd , INFINITE );
175
183
GetExitCodeProcess (process -> prochnd , & termstat );
176
- if (termstat == STILL_ACTIVE ) {
177
- TerminateProcess (process -> prochnd , termstat );
178
- }
179
-
180
184
process -> stream = NULL ;
181
- process -> inuse = 0 ;
182
185
CloseHandle (process -> prochnd );
183
186
184
187
return termstat ;
185
188
}
186
189
187
- #endif
190
+ #endif
0 commit comments