Skip to content

Commit d600862

Browse files
committed
mingw: demonstrate that all file handles are inherited by child processes
When spawning child processes, we really should be careful which file handles we let them inherit. This is doubly important on Windows, where we cannot rename, delete, or modify files if there is still a file handle open. Sadly, we have to guard this test inside #ifdef WIN32: we need to use the value of the HANDLE directly, and that concept does not exist on Linux/Unix. Signed-off-by: Johannes Schindelin <[email protected]>
1 parent 1a4ee4d commit d600862

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

t/helper/test-run-command.c

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,13 +188,58 @@ static int testsuite(int argc, const char **argv)
188188
return !!ret;
189189
}
190190

191+
static int inherit_handle(const char *argv0)
192+
{
193+
struct child_process cp = CHILD_PROCESS_INIT;
194+
char path[PATH_MAX];
195+
int tmp;
196+
197+
/* First, open an inheritable handle */
198+
sprintf(path, "out-XXXXXX");
199+
tmp = xmkstemp(path);
200+
201+
argv_array_pushl(&cp.args, argv0, "inherited-handle-child", NULL);
202+
cp.in = -1;
203+
cp.no_stdout = cp.no_stderr = 1;
204+
if (start_command(&cp) < 0)
205+
die("Could not start child process");
206+
207+
/* Then close it, and try to delete it. */
208+
close(tmp);
209+
if (unlink(path))
210+
die("Could not delete '%s'", path);
211+
212+
if (close(cp.in) < 0 || finish_command(&cp) < 0)
213+
die("Child did not finish");
214+
215+
return 0;
216+
}
217+
218+
static int inherit_handle_child(void)
219+
{
220+
struct strbuf buf = STRBUF_INIT;
221+
222+
if (strbuf_read(&buf, 0, 0) < 0)
223+
die("Could not read stdin");
224+
printf("Received %s\n", buf.buf);
225+
strbuf_release(&buf);
226+
227+
return 0;
228+
}
229+
191230
int cmd_main(int argc, const char **argv)
192231
{
193232
struct child_process proc = CHILD_PROCESS_INIT;
194233
int jobs;
195234

196235
if (argc > 1 && !strcmp(argv[1], "testsuite"))
197236
exit(testsuite(argc - 1, argv + 1));
237+
238+
if (!strcmp(argv[1], "inherited-handle"))
239+
exit(inherit_handle(argv[0]));
240+
if (!strcmp(argv[1], "inherited-handle-child"))
241+
exit(inherit_handle_child());
242+
198243
if (argc < 3)
199244
return 1;
200245
proc.argv = (const char **)argv + 2;

t/t0061-run-command.sh

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@ cat >hello-script <<-EOF
1313
EOF
1414
>empty
1515

16+
test_expect_failure MINGW 'subprocess inherits only std handles' '
17+
test-run-command inherited-handle
18+
'
19+
1620
test_expect_success 'start_command reports ENOENT' '
1721
test-run-command start-command-ENOENT ./does-not-exist
1822
'

0 commit comments

Comments
 (0)