Skip to content

Instantly share code, notes, and snippets.

@dkw72n
Created April 3, 2019 04:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkw72n/9698d145cebb129993d64c12dce32c5d to your computer and use it in GitHub Desktop.
Save dkw72n/9698d145cebb129993d64c12dce32c5d to your computer and use it in GitHub Desktop.
[windows] ensure all child processes killed when main process exit
"""
MIT License
Copyright (c) 2019 dkw72n.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import subprocess
import time
import ctypes
from _ctypes import Structure, Union, POINTER
from ctypes import *
from ctypes.wintypes import *
import os
ULONGLONG = c_ulonglong;
SIZE_T = c_size_t
LONGLONG = c_longlong
ULONG_PTR = c_void_p
class _LARGE_INTEGER(Structure):
_fields_ = [
("LowPart", DWORD),
("HighPart", LONG),
]
class LARGE_INTEGER(Union):
_anonymous_ = ('_u',)
_fields_ = [
("_u", _LARGE_INTEGER),
("u", _LARGE_INTEGER),
("QuadPart", LONGLONG)
]
class IO_COUNTERS(Structure):
_fields_ = [
("ReadOperationCount", ULONGLONG),
("WriteOperationCount", ULONGLONG),
("OtherOperationCount", ULONGLONG),
("ReadTransferCount", ULONGLONG),
("WriteTransferCount", ULONGLONG),
("OtherTransferCount", ULONGLONG)
]
class JOBOBJECT_BASIC_LIMIT_INFORMATION(Structure):
_fields_ = [
('PerProcessUserTimeLimit', LARGE_INTEGER),
('PerJobUserTimeLimit', LARGE_INTEGER),
('LimitFlags', DWORD),
('MinimumWorkingSetSize', SIZE_T),
('MaximumWorkingSetSize', SIZE_T),
('ActiveProcessLimit', DWORD),
('Affinity', ULONG_PTR),
('PriorityClass', DWORD),
('SchedulingClass', DWORD)
]
class JOBOBJECT_EXTENDED_LIMIT_INFORMATION(Structure):
_fields_ = [
('BasicLimitInformation', JOBOBJECT_BASIC_LIMIT_INFORMATION),
('IoInfo', IO_COUNTERS),
('ProcessMemoryLimit', SIZE_T),
('JobMemoryLimit', SIZE_T),
('PeakProcessMemoryUsed', SIZE_T),
('PeakJobMemoryUsed', SIZE_T)
]
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000
JobObjectBasicLimitInformation = 2
JobObjectExtendedLimitInformation = 9
CreateJobObjectW = windll.kernel32.CreateJobObjectW
CreateJobObjectW.restype = HANDLE
CreateJobObjectW.argtypes = [c_void_p, c_wchar_p]
GetCurrentProcess = windll.kernel32.GetCurrentProcess
GetCurrentProcess.restype = HANDLE
AssignProcessToJobObject = windll.kernel32.AssignProcessToJobObject
AssignProcessToJobObject.restype = BOOL
AssignProcessToJobObject.argtypes = [HANDLE, HANDLE]
GetLastError = windll.kernel32.GetLastError
OpenJobObjectW = windll.kernel32.OpenJobObjectW
TerminateJobObject = windll.kernel32.TerminateJobObject
TerminateJobObject.restype = BOOL
TerminateJobObject.argtypes = [HANDLE, c_uint]
SetInformationJobObject = windll.kernel32.SetInformationJobObject
SetInformationJobObject.restype = BOOL
SetInformationJobObject.argtypes = [HANDLE, c_int, c_void_p, DWORD]
def activate_subprocess_reaver():
hProcess = GetCurrentProcess()
hJob = CreateJobObjectW(None, 'Local\\py_win_job_%d_%d' % (hProcess, time.time()))
if hJob == 0:
return False, ("CreateJobObjectW", GetLastError())
info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION()
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
# print(sizeof(info))
if not SetInformationJobObject(hJob, JobObjectExtendedLimitInformation, pointer(info), sizeof(info)):
return False, ("SetInformationJobObject", GetLastError())
if not AssignProcessToJobObject(hJob, hProcess):
return False, ("AssignProcessToJobObject", GetLastError())
return True, None
if __name__ == '__main__':
res, err = activate_subprocess_reaver()
if not res:
raise Exception("%s Failed: %d" % err)
os.system("start cmd /K dir")
os.system("start py -2")
subprocess.Popen([r'c:\windows\system32\notepad.exe'])
time.sleep(5)
print("bye bye")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment