Skip to content

Commit 112b906

Browse files
author
Daniel Beulshausen
committed
adopt shane's popen patch
1 parent 61822fc commit 112b906

File tree

2 files changed

+14
-11
lines changed

2 files changed

+14
-11
lines changed

TSRM/tsrm_win32.c

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -74,9 +74,7 @@ static ProcessPair* process_get(FILE *stream)
7474
TWLS_FETCH();
7575

7676
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) {
8078
break;
8179
}
8280
}
@@ -96,6 +94,14 @@ static ProcessPair* process_get(FILE *stream)
9694
return ptr;
9795
}
9896

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+
99105
TSRM_API FILE* popen(const char *command, const char *type)
100106
{
101107
FILE *stream = NULL;
@@ -146,17 +152,18 @@ TSRM_API FILE* popen(const char *command, const char *type)
146152
proc = process_get(NULL);
147153

148154
if (read) {
155+
in = dupHandle(in, FALSE);
149156
fno = _open_osfhandle((long)in, _O_RDONLY | mode);
150157
CloseHandle(out);
151158
} else {
159+
out = dupHandle(out, FALSE);
152160
fno = _open_osfhandle((long)out, _O_WRONLY | mode);
153161
CloseHandle(in);
154162
}
155163

156164
stream = _fdopen(fno, type);
157165
proc->prochnd = process.hProcess;
158166
proc->stream = stream;
159-
proc->inuse = 1;
160167
return stream;
161168
}
162169

@@ -172,16 +179,12 @@ TSRM_API int pclose(FILE* stream)
172179
fflush(process->stream);
173180
fclose(process->stream);
174181

182+
WaitForSingleObject(process->prochnd, INFINITE);
175183
GetExitCodeProcess(process->prochnd, &termstat);
176-
if (termstat == STILL_ACTIVE) {
177-
TerminateProcess(process->prochnd, termstat);
178-
}
179-
180184
process->stream = NULL;
181-
process->inuse = 0;
182185
CloseHandle(process->prochnd);
183186

184187
return termstat;
185188
}
186189

187-
#endif
190+
#endif

TSRM/tsrm_win32.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,10 @@
2525

2626
#ifdef TSRM_WIN32
2727
#include <windows.h>
28+
2829
typedef struct {
2930
FILE *stream;
3031
HANDLE prochnd;
31-
int inuse;
3232
} ProcessPair;
3333

3434
typedef struct {

0 commit comments

Comments
 (0)