From 79ed8fd79bee03916a36b4c5f46c0965df082f83 Mon Sep 17 00:00:00 2001 From: Dmitry Neverov Date: Mon, 28 Oct 2019 10:39:21 +0100 Subject: [PATCH] IDEA-CR-54283: Ability to gracefully terminate process by pid GitOrigin-RevId: aefcfae5dec522b25efac2b171bd5c6b235fb9b0 --- .../execution/process/OSProcessUtil.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/platform/platform-util-io/src/com/intellij/execution/process/OSProcessUtil.java b/platform/platform-util-io/src/com/intellij/execution/process/OSProcessUtil.java index b3ab1787f42a..34a26c751ddc 100644 --- a/platform/platform-util-io/src/com/intellij/execution/process/OSProcessUtil.java +++ b/platform/platform-util-io/src/com/intellij/execution/process/OSProcessUtil.java @@ -10,6 +10,7 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jvnet.winp.WinProcess; +import org.jvnet.winp.WinpException; import java.util.ArrayList; import java.util.Collections; @@ -83,6 +84,39 @@ public final class OSProcessUtil { } } + /** + * Terminates the process with the specified pid gracefully: on windows sends Ctrl-C, + * on unix sends the SIGINT signal. + * + * @throws UnsupportedOperationException if cannot interrupt the process + * + * @see KillableProcessHandler#destroyProcessGracefully() + */ + public static void terminateProcessGracefully(int pid) throws RuntimeException { + if (SystemInfo.isWindows) { + if (Registry.is("disable.winp")) { + throw new UnsupportedOperationException("Cannot terminate process, disable.winp=true"); + } + else { + try { + // there is no need to check return value: `sendCtrlC` either returns + // true or throws exception. + //noinspection ResultOfMethodCallIgnored + createWinProcess(pid).sendCtrlC(); + } + catch (WinpException e) { + throw new UnsupportedOperationException("Failed to terminate process", e); + } + } + } + else if (SystemInfo.isUnix) { + UnixProcessManager.sendSignal(pid, UnixProcessManager.SIGINT); + } + else { + throw new UnsupportedOperationException("Graceful termination is not supported for " + SystemInfo.getOsNameAndVersion()); + } + } + static void logSkippedActionWithTerminatedProcess(@NotNull Process process, @NotNull String actionName, @Nullable String commandLine) { Integer pid = null; try {