Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,11 @@ jobs:
uses: devlooped/actions-dotnet-env@v1

- name: 🙏 build
# The 'any' build comes first: packing the solution packs stop.any from its output.
run: |
dotnet build -m:1 -bl:build.binlog -p:RuntimeIdentifiers=any
dotnet restore -bl:restore.binlog -p:RuntimeIdentifiers=any
dotnet build src/stop/stop.csproj -bl:runtime.binlog -p:RuntimeIdentifiers=any -r any
dotnet build -m:1 -bl:build.binlog -p:RuntimeIdentifiers=any

- name: 🧪 test
shell: pwsh
Expand Down
13 changes: 12 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,16 @@

- `src/stop/stop.csproj` targets `net10.0` only.
- Hybrid Native AOT/CoreCLR tool packaging is opt-in via `HybridToolPackage=true`.
- Keep `.github/workflows/build.yml` on the default non-AOT package path for fast CI and dogfooding.
- Keep `.github/workflows/build.yml` on the default non-AOT package path for fast CI and dogfooding. It builds with `RuntimeIdentifiers=any`, for which `stop.csproj` turns AOT off: the .NET 11 SDK drops `any` from an AOT tool's RID packages and, with none left, fails with a circular dependency on `_CreateRIDSpecificToolPackages`. It builds `-r any` before the solution, since packing the solution packs `stop.any` from that build's output.
- In `.github/workflows/publish.yml`, publish RID-specific packages and the `any` fallback before publishing the top-level pointer package.

## Stopping

The stop logic in `src/stop/Program.cs` follows ndx's `ProcessStop`/`ChildProcess` (github.com/devlooped/ndx), adapted to stopping a process we did not start:

- Windows: `WM_CLOSE` first, then Ctrl+C through the `stopr` helper, which attaches to the target's console. A GUI app started from a shell has no console, and `stopr` would otherwise attach to an ancestor's console and report a Ctrl+C the app never gets. Console windows (`ConsoleWindowClass`, `PseudoConsoleWindow`) report the console app as owner and are never sent `WM_CLOSE`, which would close the console instead of sending Ctrl+C.
- NeoAstra apps: when a `NeoAstra.Window` is present, only unowned top-level frames of that class get `WM_CLOSE`; the message on its other windows destroys them and leaves an app that cannot exit.
- Unix: libc `kill()` with SIGINT to the target's process group (libc `getpgid()`), or to the target alone when that group is our own. The `kill` tool is not used: procps-ng takes `-INT -<pgid>` without signaling and exits with 0.
- The wait ends early on stopped/zombie state or a quiesced process group only on Linux, where `/proc` gives them; on macOS it waits for `Process.HasExited`.
- The descendants of the target (`ProcessTree`) are recorded before the signal and while waiting, since they are reparented once it exits, then waited for within the same timeout.
- Killing is opt-in (`--kill`), after the timeout; ndx always kills because it must restart the tool.
13 changes: 9 additions & 4 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ PowerShell's `Stop-Process` (and the underlying `TerminateProcess` on Windows /
`dnx stop` sends **SIGINT** instead — the same signal as pressing Ctrl+C — which lets the process shut down on its own terms. On Windows this is non-trivial to do programmatically; for console apps it requires detaching from the current console, attaching to the target process's console group, and calling `GenerateConsoleCtrlEvent`. For GUI apps (including UWP apps like Calculator), it sends `WM_CLOSE` to the app's windows — the same as clicking the close button. This tool handles all of that transparently, cross-platform.

``` bash
dnx stop [<processId>] [--timeout <milliseconds>] [--quiet]
dnx stop [<processId>] [--timeout <milliseconds>] [--kill] [--quiet]
```

<!-- include src/stop/help.md -->
Expand All @@ -27,16 +27,21 @@ Arguments:

Options:
-t, --timeout <int?> Optional timeout in milliseconds to wait for the process to exit.
-k, --kill Kill the process and the processes it started if they do not exit within the timeout.
-q, --quiet Do not display any output.
-d, --debug Print diagnostic details about the stop operation.
--attach Attach a .NET debugger before stopping.
```

<!-- src/stop/help.md -->

If no timeout is provided, the tool will wait indefinitely for the target process to exit.
Otherwise, the process will exit with a non-zero exit code if the target process didn't
exit within the specified timeout time.
The tool also waits for the processes the target started, which got the same Ctrl+C or
SIGINT and may still be shutting down after the target exits.

If no timeout is provided, the tool will wait indefinitely for the target process and the
processes it started to exit. Otherwise, the tool will exit with a non-zero exit code if they
didn't exit within the specified timeout time, unless `--kill` is given: then whatever is
still running when the timeout expires is killed, along with its process tree.

## Piping from PowerShell

Expand Down
47 changes: 46 additions & 1 deletion src/stop/NativeMethods.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Devlooped;

static class NativeMethods
{
public const uint WmClose = 0x0010;
public const uint GaRoot = 2;
public const uint GwOwner = 4;
public const uint Th32CsSnapProcess = 0x00000002;

public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);

Expand All @@ -24,5 +28,46 @@ static class NativeMethods
[DllImport("user32.dll")]
public static extern IntPtr GetAncestor(IntPtr hwnd, uint gaFlags);

public const uint GaRoot = 2;
[DllImport("user32.dll")]
public static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID);

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "Process32FirstW")]
public static extern bool Process32First(IntPtr hSnapshot, ref ProcessEntry32 lppe);

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "Process32NextW")]
public static extern bool Process32Next(IntPtr hSnapshot, ref ProcessEntry32 lppe);

[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(IntPtr hObject);

public const int SigInt = 2;

[DllImport("libc", EntryPoint = "kill", SetLastError = true)]
public static extern int Kill(int pid, int sig);

[DllImport("libc", EntryPoint = "getpgid", SetLastError = true)]
public static extern int GetPgid(int pid);

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct ProcessEntry32
{
public uint dwSize;
public uint cntUsage;
public uint th32ProcessID;
public IntPtr th32DefaultHeapID;
public uint th32ModuleID;
public uint cntThreads;
public uint th32ParentProcessID;
public int pcPriClassBase;
public uint dwFlags;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szExeFile;
}
}
162 changes: 162 additions & 0 deletions src/stop/ProcessTree.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;

namespace Devlooped;

/// <summary>
/// Child processes of the process being stopped. After the target exits, the OS
/// reparents them, so their ids have to be recorded while the target is alive.
/// </summary>
static class ProcessTree
{
public static void AddDescendants(int root, HashSet<int> into)
{
var children = ChildrenByParent();
var queue = new Queue<int>();
queue.Enqueue(root);
foreach (var pid in into)
queue.Enqueue(pid);

var seen = new HashSet<int>();
while (queue.Count > 0)
{
var pid = queue.Dequeue();
if (!seen.Add(pid))
continue;

if (pid != root)
into.Add(pid);

if (!children.TryGetValue(pid, out var kids))
continue;

foreach (var kid in kids)
queue.Enqueue(kid);
}
}

static Dictionary<int, List<int>> ChildrenByParent()
{
var children = new Dictionary<int, List<int>>();
foreach (var (pid, ppid) in ReadParentMap())
{
if (!children.TryGetValue(ppid, out var list))
{
list = [];
children[ppid] = list;
}

list.Add(pid);
}

return children;
}

static Dictionary<int, int> ReadParentMap()
{
if (OperatingSystem.IsWindows())
return ReadWindowsParents();

if (OperatingSystem.IsLinux())
{
var proc = ReadProcParents();
if (proc.Count > 0)
return proc;
}

return ReadPsParents();
}

static Dictionary<int, int> ReadProcParents()
{
var map = new Dictionary<int, int>();
if (!Directory.Exists("/proc"))
return map;

foreach (var dir in Directory.EnumerateDirectories("/proc"))
{
if (!int.TryParse(Path.GetFileName(dir), out var pid))
continue;

try
{
var stat = File.ReadAllText(Path.Combine(dir, "stat"));
var end = stat.LastIndexOf(')');
if (end < 0 || end + 2 >= stat.Length)
continue;

var fields = stat[(end + 2)..].Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (fields.Length >= 2 && int.TryParse(fields[1], out var ppid))
map[pid] = ppid;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
}
}

return map;
}

static Dictionary<int, int> ReadPsParents()
{
var map = new Dictionary<int, int>();
try
{
using var ps = Process.Start(new ProcessStartInfo("ps", "-ax -o pid=,ppid=")
{
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
});
if (ps is null)
return map;

var text = ps.StandardOutput.ReadToEnd();
ps.WaitForExit();
foreach (var line in text.Split('\n'))
{
var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length >= 2 &&
int.TryParse(parts[0], out var pid) &&
int.TryParse(parts[1], out var ppid))
map[pid] = ppid;
}
}
catch (Exception ex) when (ex is InvalidOperationException or Win32Exception or IOException)
{
}

return map;
}

static Dictionary<int, int> ReadWindowsParents()
{
var map = new Dictionary<int, int>();
var snapshot = NativeMethods.CreateToolhelp32Snapshot(NativeMethods.Th32CsSnapProcess, 0);
if (snapshot == IntPtr.Zero || snapshot == new IntPtr(-1))
return map;

try
{
var entry = new NativeMethods.ProcessEntry32 { dwSize = (uint)Marshal.SizeOf<NativeMethods.ProcessEntry32>() };
if (!NativeMethods.Process32First(snapshot, ref entry))
return map;

do
{
map[(int)entry.th32ProcessID] = (int)entry.th32ParentProcessID;
}
while (NativeMethods.Process32Next(snapshot, ref entry));

return map;
}
finally
{
NativeMethods.CloseHandle(snapshot);
}
}
}
Loading
Loading