Skip to content

Commit d9c290c

Browse files
committed
squash! Kill also children of the process to be killed via Ctrl+C
Try to kill Win32 processes gently upon Ctrl+C When a process is terminated via TerminateProcess(), it has no chance to do anything in the way of cleaning up. This is particularly noticeable when a lengthy Git for Windows process tries to update Git's index file and leaves behind an index.lock file. Git's idea is to remove the stale index.lock file in that case, using the signal and atexit handlers available in Linux. But those signal handlers never run. Note: this is not an issue for MSYS2 processes because MSYS2 emulates Unix' signal system accurately, both for the process sending the kill signal and the process receiving it. Win32 processes do not have such a signal handler, though, instead MSYS2 shuts them down via `TerminateProcess()`. Let's use a gentler method, described in the Dr Dobb's article "A Safer Alternative to TerminateProcess()" by Andrew Tucker (July 1, 1999), http://www.drdobbs.com/a-safer-alternative-to-terminateprocess/184416547 Essentially, we inject a new thread into the running process that does nothing else than running the ExitProcess() function. If that fails, or when the process still lives on after 10 seconds, we fall back to calling TerminateProcess(), but in that case we take pains to kill also processes directly or indirectly spawned by that process; TerminateProcess() does not give any process a chance to terminate its child processes. Originally, we wanted to call the function `GenerateConsoleCtrlEvent()` for SIGTERM with console processes, but 1) that may not work as it requires a process *group* ID (i.e. the process ID of the initial process group member, which we may not have), and 2) it does not kill the process *tree* on Windows 7 and earlier. Note: we do not use the NtQueryInformationProcess() function because 1) it is marked internal and subject to change at any time of Microsoft's choosing, and 2) it does not even officially report the child/parent relationship (the pid of the parent process is stored in the `Reserved3` slot of the `PROCESS_BASIC_INFORMATION` structure). Instead, we resort to the Toolhelp32 API -- which happily also works on 64-bit Windows -- to enumerate the process tree and reconstruct the process tree rooted in the process we intend to kill. While at it, we also fix the exit status: the convention is to add 128 to the signal number, to give exit code handlers a chance to detect an "exit by signal" condition. This fixes the MSYS2 side of the bug where interrupting `git clone https://...` would send the spawned-off `git remote-https` process into the background instead of interrupting it, i.e. the clone would continue and its progress would be reported mercilessly to the console window without the user being able to do anything about it (short of firing up the task manager and killing the appropriate task manually). Note that this special-handling is only necessary when *MSYS2* handles the Ctrl+C event, e.g. when interrupting a process started from within MinTTY or any other non-cmd-based terminal emulator. If the process was started from within `cmd.exe`'s terminal window, child processes are already killed appropriately upon Ctrl+C. Signed-off-by: Johannes Schindelin <[email protected]>
1 parent 82014d1 commit d9c290c

File tree

3 files changed

+123
-61
lines changed

3 files changed

+123
-61
lines changed

winsup/cygwin/exceptions.cc

+2-4
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ details. */
2727
#include "child_info.h"
2828
#include "ntdll.h"
2929
#include "exception.h"
30+
#include "cygwin/exit_process.h"
3031

3132
/* Definitions for code simplification */
3233
#ifdef __x86_64__
@@ -1547,10 +1548,7 @@ sigpacket::process ()
15471548
if (have_execed)
15481549
{
15491550
sigproc_printf ("terminating captive process");
1550-
if ((sigExeced = si.si_signo) == SIGINT)
1551-
kill_process_tree (GetProcessId (ch_spawn), sigExeced = si.si_signo);
1552-
else
1553-
TerminateProcess (ch_spawn, sigExeced = si.si_signo);
1551+
exit_process (ch_spawn, 128 + (sigExeced = si.si_signo));
15541552
}
15551553
/* Dispatch to the appropriate function. */
15561554
sigproc_printf ("signal %d, signal handler %p", si.si_signo, handler);
+121
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
// vim: ts=99 sw=2
2+
#ifndef EXIT_PROCESS_H
3+
#define EXIT_PROCESS_H
4+
5+
/*
6+
* This file contains functions to terminate a Win32 process, as gently as
7+
* possible.
8+
*
9+
* At first, we will attempt to inject a thread that calls ExitProcess(). If
10+
* that fails, we will fall back to terminating the entire process tree.
11+
*
12+
* As we do not want to export this function in the MSYS2 runtime, these
13+
* functions are marked as file-local.
14+
*/
15+
16+
#include <tlhelp32.h>
17+
18+
/**
19+
* Terminates the process corresponding to the process ID and all of its
20+
* directly and indirectly spawned subprocesses.
21+
*/
22+
static int
23+
terminate_process_tree(HANDLE main_process, int exit_code)
24+
{
25+
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
26+
PROCESSENTRY32 entry;
27+
DWORD pids[16384];
28+
int max_len = sizeof(pids) / sizeof(*pids), i, len, ret = 0;
29+
pid_t pid = GetProcessId(main_process);
30+
31+
pids[0] = (DWORD) pid;
32+
len = 1;
33+
34+
/*
35+
* Even if Process32First()/Process32Next() seem to traverse the
36+
* processes in topological order (i.e. parent processes before
37+
* child processes), there is nothing in the Win32 API documentation
38+
* suggesting that this is guaranteed.
39+
*
40+
* Therefore, run through them at least twice and stop when no more
41+
* process IDs were added to the list.
42+
*/
43+
for (;;)
44+
{
45+
int orig_len = len;
46+
47+
memset(&entry, 0, sizeof(entry));
48+
entry.dwSize = sizeof(entry);
49+
50+
if (!Process32First(snapshot, &entry))
51+
break;
52+
53+
do
54+
{
55+
for (i = len - 1; i >= 0; i--)
56+
{
57+
if (pids[i] == entry.th32ProcessID)
58+
break;
59+
if (pids[i] == entry.th32ParentProcessID)
60+
pids[len++] = entry.th32ProcessID;
61+
}
62+
}
63+
while (len < max_len && Process32Next(snapshot, &entry));
64+
65+
if (orig_len == len || len >= max_len)
66+
break;
67+
}
68+
69+
for (i = len - 1; i >= 0; i--)
70+
{
71+
HANDLE process = i == 0 ? main_process :
72+
OpenProcess(PROCESS_TERMINATE, FALSE, pids[i]);
73+
74+
if (process)
75+
{
76+
if (!TerminateProcess(process, exit_code))
77+
ret = -1;
78+
CloseHandle(process);
79+
}
80+
}
81+
82+
return ret;
83+
}
84+
85+
/**
86+
* Inject a thread into the given process that runs ExitProcess().
87+
*
88+
* Note: as kernel32.dll is loaded before any process, the other process and
89+
* this process will have ExitProcess() at the same address.
90+
*
91+
* This function expects the process handle to have the access rights for
92+
* CreateRemoteThread(): PROCESS_CREATE_THREAD, PROCESS_QUERY_INFORMATION,
93+
* PROCESS_VM_OPERATION, PROCESS_VM_WRITE, and PROCESS_VM_READ.
94+
*
95+
* If this method fails, we fall back to running terminate_process_tree().
96+
*/
97+
static int
98+
exit_process(HANDLE process, int exit_code)
99+
{
100+
DWORD code;
101+
102+
if (GetExitCodeProcess (process, &code) && code == STILL_ACTIVE)
103+
{
104+
HINSTANCE kernel32 = GetModuleHandle("kernel32");
105+
LPTHREAD_START_ROUTINE exit_process_address =
106+
(LPTHREAD_START_ROUTINE) GetProcAddress (kernel32, "ExitProcess");
107+
DWORD thread_id;
108+
HANDLE thread = CreateRemoteThread (process, NULL, 0,
109+
exit_process_address,
110+
(PVOID)exit_code, 0, &thread_id);
111+
112+
if (!thread)
113+
return terminate_process_tree(process, exit_code);
114+
CloseHandle (thread);
115+
if (WaitForSingleObject (process, 10000) == WAIT_OBJECT_0)
116+
return 0;
117+
}
118+
return -1;
119+
}
120+
121+
#endif

winsup/cygwin/signal.cc

-57
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ Cygwin license. Please consult the file "CYGWIN_LICENSE" for
1010
details. */
1111

1212
#include "winsup.h"
13-
#include <tlhelp32.h>
1413
#include <stdlib.h>
1514
#include <sys/cygwin.h>
1615
#include "pinfo.h"
@@ -359,62 +358,6 @@ killpg (pid_t pgrp, int sig)
359358
return kill (-pgrp, sig);
360359
}
361360

362-
/**
363-
* Terminates the process corresponding to the process ID and all of its
364-
* directly and indirectly spawned subprocesses.
365-
*/
366-
extern "C" void
367-
kill_process_tree(pid_t pid, int sig)
368-
{
369-
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
370-
PROCESSENTRY32 entry;
371-
DWORD pids[16384];
372-
int max_len = sizeof(pids) / sizeof(*pids), i, len;
373-
374-
pids[0] = (DWORD) pid;
375-
len = 1;
376-
377-
/*
378-
* Even if Process32First()/Process32Next() seem to traverse the
379-
* processes in topological order (i.e. parent processes before
380-
* child processes), there is nothing in the Win32 API documentation
381-
* suggesting that this is guaranteed.
382-
*
383-
* Therefore, run through them at least twice and stop when no more
384-
* process IDs were added to the list.
385-
*/
386-
for (;;) {
387-
int orig_len = len;
388-
389-
memset(&entry, 0, sizeof(entry));
390-
entry.dwSize = sizeof(entry);
391-
392-
if (!Process32First(snapshot, &entry))
393-
break;
394-
395-
do {
396-
for (i = len - 1; i >= 0; i--) {
397-
if (pids[i] == entry.th32ProcessID)
398-
break;
399-
if (pids[i] == entry.th32ParentProcessID)
400-
pids[len++] = entry.th32ProcessID;
401-
}
402-
} while (len < max_len && Process32Next(snapshot, &entry));
403-
404-
if (orig_len == len || len >= max_len)
405-
break;
406-
}
407-
408-
for (i = len - 1; i >= 0; i--) {
409-
HANDLE process = OpenProcess(PROCESS_TERMINATE, FALSE, pids[i]);
410-
411-
if (process) {
412-
TerminateProcess(process, sig << 8);
413-
CloseHandle(process);
414-
}
415-
}
416-
}
417-
418361
extern "C" void
419362
abort (void)
420363
{

0 commit comments

Comments
 (0)