Last active
December 16, 2024 07:03
-
-
Save hallazzang/76f3970bfc949831808bbebc8ca15209 to your computer and use it in GitHub Desktop.
[go] (Windows) ensure all child processes are killed when main program exits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"os/exec" | |
"unsafe" | |
"golang.org/x/sys/windows" | |
) | |
// We use this struct to retreive process handle(which is unexported) | |
// from os.Process using unsafe operation. | |
type process struct { | |
Pid int | |
Handle uintptr | |
} | |
func main() { | |
job, err := windows.CreateJobObject(nil, nil) | |
if err != nil { | |
panic(err) | |
} | |
defer windows.CloseHandle(job) | |
info := windows.JOBOBJECT_EXTENDED_LIMIT_INFORMATION{ | |
BasicLimitInformation: windows.JOBOBJECT_BASIC_LIMIT_INFORMATION{ | |
LimitFlags: windows.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, | |
}, | |
} | |
if _, err := windows.SetInformationJobObject( | |
job, | |
windows.JobObjectExtendedLimitInformation, | |
uintptr(unsafe.Pointer(&info)), | |
uint32(unsafe.Sizeof(info))); err != nil { | |
panic(err) | |
} | |
cmd := exec.Command("notepad.exe", "noname") | |
if err := cmd.Start(); err != nil { | |
panic(err) | |
} | |
if err := windows.AssignProcessToJobObject( | |
job, | |
windows.Handle((*process)(unsafe.Pointer(cmd.Process)).Handle)); err != nil { | |
panic(err) | |
} | |
if err := cmd.Wait(); err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
super helpful!