From 61217f06edae2c355f3dd3bc82d5aeb2b38d25a6 Mon Sep 17 00:00:00 2001 From: Andreas Herrmann Date: Tue, 29 Oct 2019 15:18:36 +0100 Subject: [PATCH] script_runner: Kill sub-processes on exit --- bazel_tools/script_runner.bzl | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/bazel_tools/script_runner.bzl b/bazel_tools/script_runner.bzl index 777b83f10e22..59eae1a6fe7a 100644 --- a/bazel_tools/script_runner.bzl +++ b/bazel_tools/script_runner.bzl @@ -75,6 +75,10 @@ def script_runner(ctx, name, script, data = [], collect_data = True, interpreter #include +#ifdef _WIN32 +#include +#endif + #include "tools/cpp/runfiles/runfiles.h" using bazel::tools::cpp::runfiles::Runfiles; @@ -100,6 +104,19 @@ int main(int argc, char** argv) {{ argv_new[argc + 1] = nullptr; #ifdef _WIN32 + // Create a JobObject to ensure that spawned subprocesses are killed. + // See https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createjobobjecta. + std::unique_ptr::type, std::function> job_object( + CreateJobObject(NULL, NULL), + [](HANDLE h) {{ CloseHandle(h); }} + ); + // Ensure that sub-processes are assigned to the same JobObject. + AssignProcessToJobObject(job_object.get(), GetCurrentProcess()); + // Ensure that sub-processes are killed on exit. + JOBOBJECT_EXTENDED_LIMIT_INFORMATION info = {{0}}; + info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + SetInformationJobObject(job_object.get(), JobObjectExtendedLimitInformation, &info, sizeof(info)); + // On Windows execv does not behave as expected, // see https://github.com/austriancoder/ccache-win32/issues/3#issuecomment-120084234. int status = spawnv(_P_WAIT, argv_new[0], argv_new.get());