noorphan 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
noorphan-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: noorphan
3
+ Version: 0.1.0
4
+ Summary: Run a command so that every descendant dies when it exits or the wrapper is killed.
5
+ License: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/maximusrufus/noorphan
7
+ Project-URL: Source, https://github.com/maximusrufus/noorphan
8
+ Project-URL: Issues, https://github.com/maximusrufus/noorphan/issues
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Operating System :: Microsoft :: Windows
13
+ Classifier: Operating System :: POSIX :: Linux
14
+ Classifier: Operating System :: MacOS
15
+ Classifier: Topic :: System :: Systems Administration
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Provides-Extra: psutil
20
+ Requires-Dist: psutil; extra == "psutil"
21
+ Provides-Extra: test
22
+ Requires-Dist: pytest; extra == "test"
23
+ Dynamic: license-file
24
+
25
+ <p align="center">
26
+ <img src="assets/logo.svg" alt="noorphan logo" width="96" height="96">
27
+ </p>
28
+
29
+ <h1 align="center">noorphan</h1>
30
+
31
+ <p align="center"><b>When your command dies, its children die with it.</b></p>
32
+
33
+ <p align="center">
34
+ <a href="https://github.com/maximusrufus/noorphan/actions/workflows/ci.yml"><img src="https://github.com/maximusrufus/noorphan/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
35
+ <img src="https://img.shields.io/badge/python-3.10%2B-blue" alt="Python 3.10+">
36
+ <img src="https://img.shields.io/badge/license-Apache--2.0-green" alt="License: Apache-2.0">
37
+ </p>
38
+
39
+ Run a command and make sure every descendant dies when the command exits,
40
+ the wrapper exits, or the wrapper is killed (see Limits). Pure standard library
41
+ (`psutil` is an optional extra used by `scan` when present).
42
+
43
+ ## Quick start
44
+
45
+ pip install .
46
+ noorphan -- python my_server.py # children die with it; exit code is forwarded
47
+ noorphan scan # list orphaned processes (pid, name, age, command line)
48
+ make demo # or: python demo.py
49
+
50
+ ## Before / after
51
+
52
+ `python demo.py` starts a parent that spawns three sleeper grandchildren, then
53
+ kills the parent. Output of a real run on Windows:
54
+
55
+ orphans without wrapper: 3
56
+ orphans with wrapper: 0
57
+
58
+ ## Why
59
+
60
+ - Dev servers that spawn workers which keep running after the server is stopped.
61
+ - Test runners that leave helper processes behind when interrupted or killed.
62
+ - AI coding agents that start background processes and leave them behind.
63
+
64
+ ## Mechanisms
65
+
66
+ | Platform | Mechanism |
67
+ |----------|-----------|
68
+ | Windows | Starts the child paused (not yet running), assigns it to a Job Object (`JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`, via ctypes), then resumes it |
69
+ | Linux | `PR_SET_PDEATHSIG` on the child, `PR_SET_CHILD_SUBREAPER` on the wrapper, own session with process-group kill, watcher process for forced wrapper death |
70
+ | macOS | `start_new_session`, process-group kill on exit, watcher using kqueue `NOTE_EXIT` on the wrapper plus pipe EOF |
71
+
72
+ ## Limits
73
+
74
+ - On POSIX a descendant that moves itself into a new session escapes the
75
+ group kill (Linux still catches it on a normal wrapper exit via the subreaper).
76
+ - Interactive commands lose their controlling terminal on POSIX (the child runs
77
+ in its own session), so full-screen programs and shells are not supported.
78
+ - Signals (interrupt, terminate, hangup) are forwarded to the child group; after a
79
+ 3 s grace period the group is killed, and the exit code is then 137 on POSIX.
80
+ - The watcher kills by process-group id; if the whole group is gone and the id is
81
+ reused before the watcher fires, an unrelated group could be hit (narrow window).
82
+ - Not for multithreaded host processes: the Linux path uses a pre-exec hook, which
83
+ is unsafe when other threads exist at fork time.
84
+
85
+ ## Platform status
86
+
87
+ | Platform | Status |
88
+ |----------|--------|
89
+ | Windows | tested (CI) |
90
+ | Linux | tested (CI) |
91
+ | macOS | tested (CI) |
92
+
93
+ CI: Python 3.10 and 3.13 on ubuntu-latest, macos-latest and windows-latest
94
+ ([run](https://github.com/maximusrufus/noorphan/actions/runs/42339468142)).
95
+
96
+ ## License
97
+
98
+ Apache-2.0, see `LICENSE`.
@@ -0,0 +1,74 @@
1
+ <p align="center">
2
+ <img src="assets/logo.svg" alt="noorphan logo" width="96" height="96">
3
+ </p>
4
+
5
+ <h1 align="center">noorphan</h1>
6
+
7
+ <p align="center"><b>When your command dies, its children die with it.</b></p>
8
+
9
+ <p align="center">
10
+ <a href="https://github.com/maximusrufus/noorphan/actions/workflows/ci.yml"><img src="https://github.com/maximusrufus/noorphan/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
11
+ <img src="https://img.shields.io/badge/python-3.10%2B-blue" alt="Python 3.10+">
12
+ <img src="https://img.shields.io/badge/license-Apache--2.0-green" alt="License: Apache-2.0">
13
+ </p>
14
+
15
+ Run a command and make sure every descendant dies when the command exits,
16
+ the wrapper exits, or the wrapper is killed (see Limits). Pure standard library
17
+ (`psutil` is an optional extra used by `scan` when present).
18
+
19
+ ## Quick start
20
+
21
+ pip install .
22
+ noorphan -- python my_server.py # children die with it; exit code is forwarded
23
+ noorphan scan # list orphaned processes (pid, name, age, command line)
24
+ make demo # or: python demo.py
25
+
26
+ ## Before / after
27
+
28
+ `python demo.py` starts a parent that spawns three sleeper grandchildren, then
29
+ kills the parent. Output of a real run on Windows:
30
+
31
+ orphans without wrapper: 3
32
+ orphans with wrapper: 0
33
+
34
+ ## Why
35
+
36
+ - Dev servers that spawn workers which keep running after the server is stopped.
37
+ - Test runners that leave helper processes behind when interrupted or killed.
38
+ - AI coding agents that start background processes and leave them behind.
39
+
40
+ ## Mechanisms
41
+
42
+ | Platform | Mechanism |
43
+ |----------|-----------|
44
+ | Windows | Starts the child paused (not yet running), assigns it to a Job Object (`JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`, via ctypes), then resumes it |
45
+ | Linux | `PR_SET_PDEATHSIG` on the child, `PR_SET_CHILD_SUBREAPER` on the wrapper, own session with process-group kill, watcher process for forced wrapper death |
46
+ | macOS | `start_new_session`, process-group kill on exit, watcher using kqueue `NOTE_EXIT` on the wrapper plus pipe EOF |
47
+
48
+ ## Limits
49
+
50
+ - On POSIX a descendant that moves itself into a new session escapes the
51
+ group kill (Linux still catches it on a normal wrapper exit via the subreaper).
52
+ - Interactive commands lose their controlling terminal on POSIX (the child runs
53
+ in its own session), so full-screen programs and shells are not supported.
54
+ - Signals (interrupt, terminate, hangup) are forwarded to the child group; after a
55
+ 3 s grace period the group is killed, and the exit code is then 137 on POSIX.
56
+ - The watcher kills by process-group id; if the whole group is gone and the id is
57
+ reused before the watcher fires, an unrelated group could be hit (narrow window).
58
+ - Not for multithreaded host processes: the Linux path uses a pre-exec hook, which
59
+ is unsafe when other threads exist at fork time.
60
+
61
+ ## Platform status
62
+
63
+ | Platform | Status |
64
+ |----------|--------|
65
+ | Windows | tested (CI) |
66
+ | Linux | tested (CI) |
67
+ | macOS | tested (CI) |
68
+
69
+ CI: Python 3.10 and 3.13 on ubuntu-latest, macos-latest and windows-latest
70
+ ([run](https://github.com/maximusrufus/noorphan/actions/runs/42339468142)).
71
+
72
+ ## License
73
+
74
+ Apache-2.0, see `LICENSE`.
@@ -0,0 +1,3 @@
1
+ """noorphan: no orphaned descendants."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,28 @@
1
+ import sys
2
+
3
+
4
+ def main(argv=None) -> int:
5
+ argv = list(sys.argv[1:] if argv is None else argv)
6
+ if argv[:1] == ["scan"]:
7
+ from .scan import main as scan_main
8
+
9
+ return scan_main()
10
+ if argv[:1] == ["--"]:
11
+ argv = argv[1:]
12
+ elif not argv or argv[0] in ("-h", "--help"):
13
+ print("usage: noorphan -- <cmd> [args]\n noorphan scan")
14
+ return 2
15
+ if not argv:
16
+ print("noorphan: no command given", file=sys.stderr)
17
+ return 2
18
+ from .core import run
19
+
20
+ try:
21
+ return run(argv)
22
+ except FileNotFoundError as e:
23
+ print(f"noorphan: {e}", file=sys.stderr)
24
+ return 127
25
+
26
+
27
+ if __name__ == "__main__":
28
+ sys.exit(main())
@@ -0,0 +1,31 @@
1
+ import os
2
+ import sys
3
+
4
+
5
+ def pid_alive(pid: int) -> bool:
6
+ if sys.platform == "win32":
7
+ import ctypes
8
+
9
+ k = ctypes.WinDLL("kernel32", use_last_error=True)
10
+ k.OpenProcess.restype = ctypes.c_void_p
11
+ k.OpenProcess.argtypes = [ctypes.c_ulong, ctypes.c_int, ctypes.c_ulong]
12
+ k.GetExitCodeProcess.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
13
+ k.CloseHandle.argtypes = [ctypes.c_void_p]
14
+ h = k.OpenProcess(0x1000, False, pid) # QUERY_LIMITED_INFORMATION
15
+ if not h:
16
+ return False
17
+ code = ctypes.c_ulong()
18
+ ok = k.GetExitCodeProcess(h, ctypes.byref(code))
19
+ k.CloseHandle(h)
20
+ return bool(ok) and code.value == 259
21
+ try:
22
+ os.kill(pid, 0)
23
+ except ProcessLookupError:
24
+ return False
25
+ except PermissionError:
26
+ return True
27
+ try:
28
+ with open(f"/proc/{pid}/stat") as f:
29
+ return f.read().rsplit(")", 1)[1].split()[0] != "Z"
30
+ except OSError:
31
+ return True
@@ -0,0 +1,42 @@
1
+ """Watcher: kills a process group when the wrapper dies (pipe EOF / kqueue exit)."""
2
+
3
+ import os
4
+ import select
5
+ import signal
6
+ import sys
7
+
8
+
9
+ def main() -> None:
10
+ pgid, wrapper = int(sys.argv[1]), int(sys.argv[2])
11
+ fd = sys.stdin.fileno()
12
+ if hasattr(select, "kqueue"):
13
+ kq = select.kqueue()
14
+ evs = [
15
+ select.kevent(fd, select.KQ_FILTER_READ, select.KQ_EV_ADD),
16
+ select.kevent(
17
+ wrapper, select.KQ_FILTER_PROC, select.KQ_EV_ADD, select.KQ_NOTE_EXIT
18
+ ),
19
+ ]
20
+ try:
21
+ kq.control(evs, 0, 0)
22
+ except OSError:
23
+ pass
24
+ while True:
25
+ got = kq.control(None, 4, None)
26
+ if any(e.filter == select.KQ_FILTER_PROC for e in got):
27
+ break
28
+ if any(e.filter == select.KQ_FILTER_READ for e in got):
29
+ if os.read(fd, 1) != b"x":
30
+ break
31
+ return
32
+ else:
33
+ if os.read(fd, 1) == b"x":
34
+ return
35
+ try:
36
+ os.killpg(pgid, signal.SIGKILL)
37
+ except OSError:
38
+ pass
39
+
40
+
41
+ if __name__ == "__main__":
42
+ main()
@@ -0,0 +1,192 @@
1
+ import os
2
+ import signal
3
+ import subprocess
4
+ import sys
5
+ import time
6
+
7
+ GRACE = 3.0
8
+
9
+
10
+ def run(cmd: list[str]) -> int:
11
+ if sys.platform == "win32":
12
+ return _run_windows(cmd)
13
+ return _run_posix(cmd)
14
+
15
+
16
+ # ---------------------------------------------------------------- Windows
17
+ def _run_windows(cmd):
18
+ import ctypes
19
+ from ctypes import wintypes as w
20
+
21
+ k = ctypes.WinDLL("kernel32", use_last_error=True)
22
+
23
+ class IOC(ctypes.Structure):
24
+ _fields_ = [(n, ctypes.c_ulonglong) for n in ("a", "b", "c", "d", "e", "f")]
25
+
26
+ class BASIC(ctypes.Structure):
27
+ _fields_ = [
28
+ ("PerProcessUserTimeLimit", ctypes.c_longlong),
29
+ ("PerJobUserTimeLimit", ctypes.c_longlong),
30
+ ("LimitFlags", w.DWORD),
31
+ ("MinimumWorkingSetSize", ctypes.c_size_t),
32
+ ("MaximumWorkingSetSize", ctypes.c_size_t),
33
+ ("ActiveProcessLimit", w.DWORD),
34
+ ("Affinity", ctypes.c_size_t),
35
+ ("PriorityClass", w.DWORD),
36
+ ("SchedulingClass", w.DWORD),
37
+ ]
38
+
39
+ class EXT(ctypes.Structure):
40
+ _fields_ = [
41
+ ("Basic", BASIC),
42
+ ("Io", IOC),
43
+ ("ProcessMemoryLimit", ctypes.c_size_t),
44
+ ("JobMemoryLimit", ctypes.c_size_t),
45
+ ("PeakProcessMemoryUsed", ctypes.c_size_t),
46
+ ("PeakJobMemoryUsed", ctypes.c_size_t),
47
+ ]
48
+
49
+ k.CreateJobObjectW.restype = w.HANDLE
50
+ k.CreateJobObjectW.argtypes = [ctypes.c_void_p, w.LPCWSTR]
51
+ k.SetInformationJobObject.argtypes = [
52
+ w.HANDLE,
53
+ ctypes.c_int,
54
+ ctypes.c_void_p,
55
+ w.DWORD,
56
+ ]
57
+ k.AssignProcessToJobObject.argtypes = [w.HANDLE, w.HANDLE]
58
+ k.TerminateJobObject.argtypes = [w.HANDLE, w.UINT]
59
+ k.CloseHandle.argtypes = [w.HANDLE]
60
+
61
+ job = k.CreateJobObjectW(None, None)
62
+ if not job:
63
+ raise ctypes.WinError(ctypes.get_last_error())
64
+ info = EXT()
65
+ info.Basic.LimitFlags = 0x2000 # KILL_ON_JOB_CLOSE
66
+ if not k.SetInformationJobObject(job, 9, ctypes.byref(info), ctypes.sizeof(info)):
67
+ raise ctypes.WinError(ctypes.get_last_error())
68
+ # Start paused (creation flag 0x4) so no descendant can exist before the child is in the job.
69
+ p = subprocess.Popen(cmd, creationflags=0x4)
70
+ try:
71
+ if not k.AssignProcessToJobObject(job, int(p._handle)):
72
+ err = ctypes.get_last_error()
73
+ p.kill()
74
+ raise ctypes.WinError(err)
75
+ nt = ctypes.WinDLL("ntdll")
76
+ nt.NtResumeProcess.argtypes = [w.HANDLE]
77
+ if nt.NtResumeProcess(int(p._handle)) != 0:
78
+ p.kill()
79
+ raise OSError("NtResumeProcess failed")
80
+ while True:
81
+ try:
82
+ return p.wait()
83
+ except KeyboardInterrupt:
84
+ pass # console delivers Ctrl-C to the child too; keep waiting
85
+ finally:
86
+ k.TerminateJobObject(job, 1)
87
+ k.CloseHandle(job)
88
+
89
+
90
+ # ------------------------------------------------------------------ POSIX
91
+ def _children_of(me):
92
+ out = []
93
+ try:
94
+ names = os.listdir("/proc")
95
+ except OSError:
96
+ return out
97
+ for n in names:
98
+ if n.isdigit():
99
+ try:
100
+ with open(f"/proc/{n}/stat") as f:
101
+ if int(f.read().rsplit(")", 1)[1].split()[1]) == me:
102
+ out.append(int(n))
103
+ except (OSError, ValueError, IndexError):
104
+ pass
105
+ return out
106
+
107
+
108
+ def _reap_all():
109
+ me = os.getpid()
110
+ for _ in range(20):
111
+ kids = _children_of(me)
112
+ if not kids:
113
+ break
114
+ for c in kids:
115
+ try:
116
+ os.kill(c, signal.SIGKILL)
117
+ except OSError:
118
+ pass
119
+ try:
120
+ while os.waitpid(-1, os.WNOHANG)[0]:
121
+ pass
122
+ except ChildProcessError:
123
+ pass
124
+
125
+
126
+ def _run_posix(cmd):
127
+ linux = sys.platform.startswith("linux")
128
+ libc = None
129
+ if linux:
130
+ import ctypes
131
+
132
+ libc = ctypes.CDLL(None, use_errno=True)
133
+ libc.prctl(36, 1, 0, 0, 0) # PR_SET_CHILD_SUBREAPER
134
+
135
+ expected_ppid = os.getpid()
136
+
137
+ def pre():
138
+ if libc is not None:
139
+ libc.prctl(1, signal.SIGKILL, 0, 0, 0) # PR_SET_PDEATHSIG
140
+ if os.getppid() != expected_ppid: # wrapper died before prctl took effect
141
+ os._exit(1)
142
+
143
+ p = subprocess.Popen(cmd, start_new_session=True, preexec_fn=pre if linux else None)
144
+ pgid = p.pid
145
+ watcher = subprocess.Popen(
146
+ [sys.executable, "-m", "noorphan._watch", str(pgid), str(os.getpid())],
147
+ stdin=subprocess.PIPE,
148
+ start_new_session=True,
149
+ )
150
+
151
+ deadline = [None]
152
+
153
+ def forward(signum, _frame):
154
+ try:
155
+ os.killpg(pgid, signum)
156
+ except OSError:
157
+ pass
158
+ if deadline[0] is None:
159
+ deadline[0] = time.monotonic() + GRACE
160
+
161
+ saved = {}
162
+ for sg in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
163
+ saved[sg] = signal.signal(sg, forward)
164
+ try:
165
+ while True:
166
+ try:
167
+ rc = p.wait(timeout=0.1)
168
+ break
169
+ except subprocess.TimeoutExpired:
170
+ if deadline[0] is not None and time.monotonic() > deadline[0]:
171
+ try:
172
+ os.killpg(pgid, signal.SIGKILL)
173
+ except OSError:
174
+ pass
175
+ if rc < 0:
176
+ rc = 128 - rc
177
+ return rc
178
+ finally:
179
+ for sg, old in saved.items():
180
+ signal.signal(sg, old)
181
+ try:
182
+ os.killpg(pgid, signal.SIGKILL)
183
+ except OSError:
184
+ pass
185
+ try:
186
+ watcher.stdin.write(b"x")
187
+ watcher.stdin.close()
188
+ watcher.wait(timeout=5)
189
+ except Exception:
190
+ pass
191
+ if linux:
192
+ _reap_all()
@@ -0,0 +1,128 @@
1
+ import json
2
+ import os
3
+ import re
4
+ import subprocess
5
+ import sys
6
+ import time
7
+
8
+
9
+ def _list_procs():
10
+ """Yield dicts: pid, ppid, name, start (epoch), cmd."""
11
+ try:
12
+ import psutil
13
+
14
+ for pr in psutil.process_iter(
15
+ ["pid", "ppid", "name", "create_time", "cmdline"]
16
+ ):
17
+ i = pr.info
18
+ yield {
19
+ "pid": i["pid"],
20
+ "ppid": i["ppid"] or 0,
21
+ "name": i["name"] or "",
22
+ "start": i["create_time"] or 0,
23
+ "cmd": " ".join(i["cmdline"] or []),
24
+ }
25
+ return
26
+ except ImportError:
27
+ pass
28
+ if sys.platform == "win32":
29
+ ps = (
30
+ "Get-CimInstance Win32_Process | Select-Object ProcessId,"
31
+ "ParentProcessId,Name,CommandLine,@{n='S';e={[double]("
32
+ "([DateTimeOffset]$_.CreationDate).ToUnixTimeSeconds())}} "
33
+ "| ConvertTo-Json -Compress"
34
+ )
35
+ out = subprocess.run(
36
+ ["powershell", "-NoProfile", "-Command", ps], capture_output=True, text=True
37
+ ).stdout
38
+ data = json.loads(out or "[]")
39
+ if isinstance(data, dict):
40
+ data = [data]
41
+ for d in data:
42
+ yield {
43
+ "pid": d["ProcessId"],
44
+ "ppid": d["ParentProcessId"],
45
+ "name": d["Name"] or "",
46
+ "start": d["S"] or 0,
47
+ "cmd": d["CommandLine"] or "",
48
+ }
49
+ return
50
+ out = subprocess.run(
51
+ ["ps", "-axo", "pid=,ppid=,etime=,command="], capture_output=True, text=True
52
+ ).stdout
53
+ now = time.time()
54
+ for line in out.splitlines():
55
+ m = re.match(r"\s*(\d+)\s+(\d+)\s+(\S+)\s+(.*)", line)
56
+ if not m:
57
+ continue
58
+ pid, ppid, et, cmd = m.groups()
59
+ days = 0
60
+ if "-" in et:
61
+ d, et = et.split("-")
62
+ days = int(d)
63
+ parts = [int(x) for x in et.split(":")]
64
+ while len(parts) < 3:
65
+ parts.insert(0, 0)
66
+ age = days * 86400 + parts[0] * 3600 + parts[1] * 60 + parts[2]
67
+ yield {
68
+ "pid": int(pid),
69
+ "ppid": int(ppid),
70
+ "name": os.path.basename(cmd.split()[0]) if cmd else "",
71
+ "start": now - age,
72
+ "cmd": cmd,
73
+ }
74
+
75
+
76
+ def _boot_time():
77
+ try:
78
+ with open("/proc/uptime") as f:
79
+ return time.time() - float(f.read().split()[0])
80
+ except OSError:
81
+ pass
82
+ try:
83
+ import psutil
84
+
85
+ return psutil.boot_time()
86
+ except ImportError:
87
+ pass
88
+ if sys.platform == "darwin":
89
+ m = re.search(
90
+ r"sec = (\d+)",
91
+ subprocess.run(
92
+ ["sysctl", "-n", "kern.boottime"], capture_output=True, text=True
93
+ ).stdout,
94
+ )
95
+ if m:
96
+ return float(m.group(1))
97
+ return 0.0
98
+
99
+
100
+ def find_orphans():
101
+ procs = {p["pid"]: p for p in _list_procs()}
102
+ boot = _boot_time()
103
+ me = os.getpid()
104
+ res = []
105
+ for p in procs.values():
106
+ pid, ppid = p["pid"], p["ppid"]
107
+ if pid in (0, 1, 2, 4, me) or ppid == 2 or not p["cmd"]:
108
+ continue
109
+ par = procs.get(ppid)
110
+ if sys.platform == "win32":
111
+ orphan = par is None or par["start"] > p["start"] > 0
112
+ else:
113
+ orphan = ppid == 1 or par is None
114
+ if orphan and p["start"] >= boot:
115
+ res.append(p)
116
+ return sorted(res, key=lambda p: p["start"])
117
+
118
+
119
+ def _fmt_age(s):
120
+ s = int(max(s, 0))
121
+ return f"{s // 3600}h{s % 3600 // 60:02d}m{s % 60:02d}s"
122
+
123
+
124
+ def main() -> int:
125
+ now = time.time()
126
+ for p in find_orphans():
127
+ print(f"{p['pid']}\t{p['name']}\t{_fmt_age(now - p['start'])}\t{p['cmd']}")
128
+ return 0
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: noorphan
3
+ Version: 0.1.0
4
+ Summary: Run a command so that every descendant dies when it exits or the wrapper is killed.
5
+ License: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/maximusrufus/noorphan
7
+ Project-URL: Source, https://github.com/maximusrufus/noorphan
8
+ Project-URL: Issues, https://github.com/maximusrufus/noorphan/issues
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Operating System :: Microsoft :: Windows
13
+ Classifier: Operating System :: POSIX :: Linux
14
+ Classifier: Operating System :: MacOS
15
+ Classifier: Topic :: System :: Systems Administration
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Provides-Extra: psutil
20
+ Requires-Dist: psutil; extra == "psutil"
21
+ Provides-Extra: test
22
+ Requires-Dist: pytest; extra == "test"
23
+ Dynamic: license-file
24
+
25
+ <p align="center">
26
+ <img src="assets/logo.svg" alt="noorphan logo" width="96" height="96">
27
+ </p>
28
+
29
+ <h1 align="center">noorphan</h1>
30
+
31
+ <p align="center"><b>When your command dies, its children die with it.</b></p>
32
+
33
+ <p align="center">
34
+ <a href="https://github.com/maximusrufus/noorphan/actions/workflows/ci.yml"><img src="https://github.com/maximusrufus/noorphan/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
35
+ <img src="https://img.shields.io/badge/python-3.10%2B-blue" alt="Python 3.10+">
36
+ <img src="https://img.shields.io/badge/license-Apache--2.0-green" alt="License: Apache-2.0">
37
+ </p>
38
+
39
+ Run a command and make sure every descendant dies when the command exits,
40
+ the wrapper exits, or the wrapper is killed (see Limits). Pure standard library
41
+ (`psutil` is an optional extra used by `scan` when present).
42
+
43
+ ## Quick start
44
+
45
+ pip install .
46
+ noorphan -- python my_server.py # children die with it; exit code is forwarded
47
+ noorphan scan # list orphaned processes (pid, name, age, command line)
48
+ make demo # or: python demo.py
49
+
50
+ ## Before / after
51
+
52
+ `python demo.py` starts a parent that spawns three sleeper grandchildren, then
53
+ kills the parent. Output of a real run on Windows:
54
+
55
+ orphans without wrapper: 3
56
+ orphans with wrapper: 0
57
+
58
+ ## Why
59
+
60
+ - Dev servers that spawn workers which keep running after the server is stopped.
61
+ - Test runners that leave helper processes behind when interrupted or killed.
62
+ - AI coding agents that start background processes and leave them behind.
63
+
64
+ ## Mechanisms
65
+
66
+ | Platform | Mechanism |
67
+ |----------|-----------|
68
+ | Windows | Starts the child paused (not yet running), assigns it to a Job Object (`JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`, via ctypes), then resumes it |
69
+ | Linux | `PR_SET_PDEATHSIG` on the child, `PR_SET_CHILD_SUBREAPER` on the wrapper, own session with process-group kill, watcher process for forced wrapper death |
70
+ | macOS | `start_new_session`, process-group kill on exit, watcher using kqueue `NOTE_EXIT` on the wrapper plus pipe EOF |
71
+
72
+ ## Limits
73
+
74
+ - On POSIX a descendant that moves itself into a new session escapes the
75
+ group kill (Linux still catches it on a normal wrapper exit via the subreaper).
76
+ - Interactive commands lose their controlling terminal on POSIX (the child runs
77
+ in its own session), so full-screen programs and shells are not supported.
78
+ - Signals (interrupt, terminate, hangup) are forwarded to the child group; after a
79
+ 3 s grace period the group is killed, and the exit code is then 137 on POSIX.
80
+ - The watcher kills by process-group id; if the whole group is gone and the id is
81
+ reused before the watcher fires, an unrelated group could be hit (narrow window).
82
+ - Not for multithreaded host processes: the Linux path uses a pre-exec hook, which
83
+ is unsafe when other threads exist at fork time.
84
+
85
+ ## Platform status
86
+
87
+ | Platform | Status |
88
+ |----------|--------|
89
+ | Windows | tested (CI) |
90
+ | Linux | tested (CI) |
91
+ | macOS | tested (CI) |
92
+
93
+ CI: Python 3.10 and 3.13 on ubuntu-latest, macos-latest and windows-latest
94
+ ([run](https://github.com/maximusrufus/noorphan/actions/runs/42339468142)).
95
+
96
+ ## License
97
+
98
+ Apache-2.0, see `LICENSE`.
@@ -0,0 +1,16 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ noorphan/__init__.py
5
+ noorphan/__main__.py
6
+ noorphan/_util.py
7
+ noorphan/_watch.py
8
+ noorphan/core.py
9
+ noorphan/scan.py
10
+ noorphan.egg-info/PKG-INFO
11
+ noorphan.egg-info/SOURCES.txt
12
+ noorphan.egg-info/dependency_links.txt
13
+ noorphan.egg-info/entry_points.txt
14
+ noorphan.egg-info/requires.txt
15
+ noorphan.egg-info/top_level.txt
16
+ tests/test_noorphan.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ noorphan = noorphan.__main__:main
@@ -0,0 +1,6 @@
1
+
2
+ [psutil]
3
+ psutil
4
+
5
+ [test]
6
+ pytest
@@ -0,0 +1 @@
1
+ noorphan
@@ -0,0 +1,36 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "noorphan"
7
+ version = "0.1.0"
8
+ description = "Run a command so that every descendant dies when it exits or the wrapper is killed."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "Apache-2.0" }
12
+ dependencies = []
13
+ classifiers = [
14
+ "License :: OSI Approved :: Apache Software License",
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3.10",
17
+ "Operating System :: Microsoft :: Windows",
18
+ "Operating System :: POSIX :: Linux",
19
+ "Operating System :: MacOS",
20
+ "Topic :: System :: Systems Administration",
21
+ ]
22
+
23
+ [project.optional-dependencies]
24
+ psutil = ["psutil"]
25
+ test = ["pytest"]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/maximusrufus/noorphan"
29
+ Source = "https://github.com/maximusrufus/noorphan"
30
+ Issues = "https://github.com/maximusrufus/noorphan/issues"
31
+
32
+ [project.scripts]
33
+ noorphan = "noorphan.__main__:main"
34
+
35
+ [tool.setuptools]
36
+ packages = ["noorphan"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,137 @@
1
+ import os
2
+ import signal
3
+ import subprocess
4
+ import sys
5
+ import time
6
+
7
+ import pytest
8
+ from noorphan._util import pid_alive
9
+
10
+ PARENT = (
11
+ "import os,subprocess,sys,time\n"
12
+ "kids=[subprocess.Popen([sys.executable,'-c','import time;time.sleep(120)'])"
13
+ " for _ in range(2)]\n"
14
+ "open(sys.argv[1]+'.tmp','w').write(' '.join(str(k.pid) for k in kids))\n"
15
+ "os.replace(sys.argv[1]+'.tmp',sys.argv[1])\n"
16
+ "time.sleep(SLEEP)\n"
17
+ )
18
+
19
+
20
+ def _wait_file(path, t=20):
21
+ end = time.time() + t
22
+ while time.time() < end:
23
+ try:
24
+ txt = open(path).read().split()
25
+ if len(txt) == 2:
26
+ return [int(x) for x in txt]
27
+ except OSError:
28
+ pass
29
+ time.sleep(0.05)
30
+ raise AssertionError("grandchildren never started")
31
+
32
+
33
+ def _wrap(code, f):
34
+ return [sys.executable, "-m", "noorphan", "--", sys.executable, "-c", code, f]
35
+
36
+
37
+ def test_exit_code_forwarded():
38
+ r = subprocess.run(
39
+ [
40
+ sys.executable,
41
+ "-m",
42
+ "noorphan",
43
+ "--",
44
+ sys.executable,
45
+ "-c",
46
+ "raise SystemExit(7)",
47
+ ]
48
+ )
49
+ assert r.returncode == 7
50
+
51
+
52
+ def test_forced_kill_leaves_no_grandchildren(tmp_path):
53
+ f = str(tmp_path / "pids")
54
+ w = subprocess.Popen(_wrap(PARENT.replace("SLEEP", "120"), f))
55
+ pids = _wait_file(f)
56
+ try:
57
+ assert all(pid_alive(p) for p in pids)
58
+ w.kill()
59
+ w.wait()
60
+ end = time.time() + 10
61
+ while time.time() < end and any(pid_alive(p) for p in pids):
62
+ time.sleep(0.1)
63
+ assert [p for p in pids if pid_alive(p)] == []
64
+ finally:
65
+ for p in pids:
66
+ if pid_alive(p):
67
+ try:
68
+ os.kill(p, getattr(signal, "SIGKILL", signal.SIGTERM))
69
+ except OSError:
70
+ pass
71
+
72
+
73
+ def test_normal_exit_kills_grandchildren(tmp_path):
74
+ f = str(tmp_path / "pids")
75
+ r = subprocess.run(_wrap(PARENT.replace("SLEEP", "1.5"), f))
76
+ pids = [int(x) for x in open(f).read().split()]
77
+ time.sleep(0.5)
78
+ assert r.returncode == 0
79
+ assert not any(pid_alive(p) for p in pids)
80
+
81
+
82
+ def test_scan_runs():
83
+ r = subprocess.run(
84
+ [sys.executable, "-m", "noorphan", "scan"], capture_output=True, text=True
85
+ )
86
+ assert r.returncode == 0
87
+
88
+
89
+ def test_fast_grandchild_spawn_killed_with_wrapper(tmp_path):
90
+ f = str(tmp_path / "pid")
91
+ code = (
92
+ "import subprocess,sys,os;"
93
+ "k=subprocess.Popen([sys.executable,'-c','import time;time.sleep(120)']);"
94
+ "open(sys.argv[1]+'.t','w').write(str(k.pid));os.replace(sys.argv[1]+'.t',sys.argv[1])"
95
+ )
96
+ w = subprocess.Popen(_wrap(code, f))
97
+ end = time.time() + 20
98
+ while not os.path.exists(f) and time.time() < end:
99
+ time.sleep(0.05)
100
+ pid = int(open(f).read())
101
+ try:
102
+ w.kill()
103
+ w.wait()
104
+ end = time.time() + 10
105
+ while time.time() < end and pid_alive(pid):
106
+ time.sleep(0.1)
107
+ assert not pid_alive(pid)
108
+ finally:
109
+ if pid_alive(pid):
110
+ os.kill(pid, getattr(signal, "SIGKILL", signal.SIGTERM))
111
+
112
+
113
+ @pytest.mark.skipif(sys.platform == "win32", reason="POSIX signal forwarding")
114
+ def test_sigint_forwarded_tree_gone_exit_code(tmp_path):
115
+ f = str(tmp_path / "pids")
116
+ code = (
117
+ "import signal,sys;signal.signal(signal.SIGINT,lambda *a:sys.exit(5));"
118
+ + PARENT.replace("SLEEP", "120")
119
+ )
120
+ w = subprocess.Popen(_wrap(code, f))
121
+ pids = _wait_file(f)
122
+ time.sleep(0.5)
123
+ w.send_signal(signal.SIGINT)
124
+ assert w.wait(timeout=15) == 5
125
+ end = time.time() + 10
126
+ while time.time() < end and any(pid_alive(p) for p in pids):
127
+ time.sleep(0.1)
128
+ assert not any(pid_alive(p) for p in pids)
129
+
130
+
131
+ @pytest.mark.skipif(sys.platform == "win32", reason="POSIX signal forwarding")
132
+ def test_grace_period_kill_exit_code_137():
133
+ code = "import signal,time;signal.signal(signal.SIGINT,signal.SIG_IGN);time.sleep(60)"
134
+ w = subprocess.Popen([sys.executable, "-m", "noorphan", "--", sys.executable, "-c", code])
135
+ time.sleep(1.5)
136
+ w.send_signal(signal.SIGINT)
137
+ assert w.wait(timeout=15) == 137