├── go.mod ├── README.md ├── LICENSE ├── kill_default_platform.go └── kill_windows.go /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/jesseduffield/kill 2 | 3 | go 1.18 4 | 5 | require golang.org/x/sys v0.12.0 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kill 2 | 3 | Go package for killing processes across different platforms. Handles killing children of processes as well as the process itself. 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Jesse Duffield 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /kill_default_platform.go: -------------------------------------------------------------------------------- 1 | //go:build !windows 2 | // +build !windows 3 | 4 | package kill 5 | 6 | import ( 7 | "os/exec" 8 | "syscall" 9 | ) 10 | 11 | // Kill kills a process. If the process has Setpgid == true, then we have anticipated that it might spawn its own child processes, so we've given it a process group ID (PGID) equal to its process id (PID) and given its child processes will inherit the PGID, we can kill that group, rather than killing the process itself. 12 | func Kill(cmd *exec.Cmd) error { 13 | if cmd.Process == nil { 14 | // You can't kill a person with no body 15 | return nil 16 | } 17 | 18 | if cmd.SysProcAttr != nil && cmd.SysProcAttr.Setpgid { 19 | // minus sign means we're talking about a PGID as opposed to a PID 20 | return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) 21 | } 22 | 23 | return cmd.Process.Kill() 24 | } 25 | 26 | // PrepareForChildren ensures that child processes of this parent process will share the same group id 27 | // as the parent, meaning when the call Kill on the parent process, we'll kill 28 | // the whole group, parent and children both. Gruesome when you think about it. 29 | func PrepareForChildren(cmd *exec.Cmd) { 30 | cmd.SysProcAttr = &syscall.SysProcAttr{ 31 | Setpgid: true, 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /kill_windows.go: -------------------------------------------------------------------------------- 1 | // adapted from https://blog.csdn.net/fyxichen/article/details/51857864 2 | 3 | package kill 4 | 5 | import ( 6 | "golang.org/x/sys/windows" 7 | "os" 8 | "os/exec" 9 | "syscall" 10 | "unsafe" 11 | ) 12 | 13 | const PROCESS_ALL_ACCESS = windows.STANDARD_RIGHTS_REQUIRED | windows.SYNCHRONIZE | 0xffff 14 | 15 | func GetWindowsHandle(pid int) (handle windows.Handle, err error) { 16 | handle, err = windows.OpenProcess(PROCESS_ALL_ACCESS, false, uint32(pid)) 17 | return 18 | } 19 | 20 | func GetCreationTime(pid int) (time int64, err error) { 21 | handle, err := GetWindowsHandle(pid) 22 | if err != nil { 23 | return 24 | } 25 | defer closeHandle(HANDLE(handle)) 26 | 27 | var u syscall.Rusage 28 | err = syscall.GetProcessTimes(syscall.Handle(handle), &u.CreationTime, &u.ExitTime, &u.KernelTime, &u.UserTime) 29 | if err != nil { 30 | return 31 | } 32 | 33 | time = u.CreationTime.Nanoseconds() 34 | return 35 | } 36 | 37 | // Kill kills a process, along with any child processes it may have spawned. 38 | func Kill(cmd *exec.Cmd) error { 39 | if cmd.Process == nil { 40 | // You can't kill a person with no body 41 | return nil 42 | } 43 | 44 | ptime, err := GetCreationTime(cmd.Process.Pid) 45 | if err != nil { 46 | return err 47 | } 48 | 49 | pids := Getppids(uint32(cmd.Process.Pid), ptime) 50 | for _, pid := range pids { 51 | pro, err := os.FindProcess(int(pid)) 52 | if err != nil { 53 | continue 54 | } 55 | 56 | pro.Kill() 57 | } 58 | 59 | return nil 60 | } 61 | 62 | // PrepareForChildren ensures that child processes of this parent process will share the same group id 63 | // as the parent, meaning when the call Kill on the parent process, we'll kill 64 | // the whole group, parent and children both. Gruesome when you think about it. 65 | func PrepareForChildren(cmd *exec.Cmd) { 66 | // do nothing because on windows our Kill function handles children by default. 67 | } 68 | 69 | const ( 70 | MAX_PATH = 260 71 | TH32CS_SNAPPROCESS = 0x00000002 72 | ) 73 | 74 | type ProcessInfo struct { 75 | Name string 76 | Pid uint32 77 | PPid uint32 78 | } 79 | 80 | type PROCESSENTRY32 struct { 81 | DwSize uint32 82 | CntUsage uint32 83 | Th32ProcessID uint32 84 | Th32DefaultHeapID uintptr 85 | Th32ModuleID uint32 86 | CntThreads uint32 87 | Th32ParentProcessID uint32 88 | PcPriClassBase int32 89 | DwFlags uint32 90 | SzExeFile [MAX_PATH]uint16 91 | } 92 | 93 | type HANDLE uintptr 94 | 95 | var ( 96 | modkernel32 = syscall.NewLazyDLL("kernel32.dll") 97 | procCreateToolhelp32Snapshot = modkernel32.NewProc("CreateToolhelp32Snapshot") 98 | procProcess32First = modkernel32.NewProc("Process32FirstW") 99 | procProcess32Next = modkernel32.NewProc("Process32NextW") 100 | procCloseHandle = modkernel32.NewProc("CloseHandle") 101 | ) 102 | 103 | func Getppids(pid uint32, ptime int64) []uint32 { 104 | infos, err := GetProcs() 105 | if err != nil { 106 | return []uint32{pid} 107 | } 108 | var pids []uint32 = make([]uint32, 0, len(infos)) 109 | var index int = 0 110 | pids = append(pids, pid) 111 | 112 | var length int = len(pids) 113 | for index < length { 114 | for _, info := range infos { 115 | if info.PPid == pids[index] { 116 | ctime, err := GetCreationTime(int(info.Pid)) 117 | if err != nil { 118 | continue 119 | } 120 | 121 | if ctime >= ptime { 122 | // Only appending if child is newer than parent, otherwise PPid was reused 123 | pids = append(pids, info.Pid) 124 | } 125 | } 126 | } 127 | index += 1 128 | length = len(pids) 129 | } 130 | return pids 131 | } 132 | 133 | func GetProcs() (procs []ProcessInfo, err error) { 134 | snap := createToolhelp32Snapshot(TH32CS_SNAPPROCESS, uint32(0)) 135 | if snap == 0 { 136 | err = syscall.GetLastError() 137 | return 138 | } 139 | defer closeHandle(snap) 140 | var pe32 PROCESSENTRY32 141 | pe32.DwSize = uint32(unsafe.Sizeof(pe32)) 142 | if process32First(snap, &pe32) == false { 143 | err = syscall.GetLastError() 144 | return 145 | } 146 | procs = append(procs, ProcessInfo{syscall.UTF16ToString(pe32.SzExeFile[:260]), pe32.Th32ProcessID, pe32.Th32ParentProcessID}) 147 | for process32Next(snap, &pe32) { 148 | procs = append(procs, ProcessInfo{syscall.UTF16ToString(pe32.SzExeFile[:260]), pe32.Th32ProcessID, pe32.Th32ParentProcessID}) 149 | } 150 | return 151 | } 152 | 153 | func createToolhelp32Snapshot(flags, processId uint32) HANDLE { 154 | ret, _, _ := procCreateToolhelp32Snapshot.Call(uintptr(flags), uintptr(processId)) 155 | if ret <= 0 { 156 | return HANDLE(0) 157 | } 158 | return HANDLE(ret) 159 | } 160 | 161 | func process32First(snapshot HANDLE, pe *PROCESSENTRY32) bool { 162 | ret, _, _ := procProcess32First.Call(uintptr(snapshot), uintptr(unsafe.Pointer(pe))) 163 | return ret != 0 164 | } 165 | 166 | func process32Next(snapshot HANDLE, pe *PROCESSENTRY32) bool { 167 | ret, _, _ := procProcess32Next.Call(uintptr(snapshot), uintptr(unsafe.Pointer(pe))) 168 | return ret != 0 169 | } 170 | 171 | func closeHandle(object HANDLE) bool { 172 | ret, _, _ := procCloseHandle.Call(uintptr(object)) 173 | return ret != 0 174 | } 175 | --------------------------------------------------------------------------------