Skip to content

Instantly share code, notes, and snippets.

@molon
Forked from hallazzang/main.go
Created September 4, 2022 18:42
Show Gist options
  • Select an option

  • Save molon/4faa018fa4b1fadf89f4f7127d58dc29 to your computer and use it in GitHub Desktop.

Select an option

Save molon/4faa018fa4b1fadf89f4f7127d58dc29 to your computer and use it in GitHub Desktop.
[go] (Windows) ensure all child processes are killed when main program exits
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