job_windows.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package mobycli
  14. import (
  15. "fmt"
  16. "unsafe"
  17. "golang.org/x/sys/windows"
  18. )
  19. func init() {
  20. if err := killSubProcessesOnClose(); err != nil {
  21. fmt.Println("failed to create job:", err)
  22. }
  23. }
  24. // killSubProcessesOnClose will ensure on windows that all child processes of the current process are killed if parent is killed.
  25. func killSubProcessesOnClose() error {
  26. job, err := windows.CreateJobObject(nil, nil)
  27. if err != nil {
  28. return err
  29. }
  30. info := windows.JOBOBJECT_EXTENDED_LIMIT_INFORMATION{
  31. BasicLimitInformation: windows.JOBOBJECT_BASIC_LIMIT_INFORMATION{
  32. LimitFlags: windows.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
  33. },
  34. }
  35. if _, err := windows.SetInformationJobObject(
  36. job,
  37. windows.JobObjectExtendedLimitInformation,
  38. uintptr(unsafe.Pointer(&info)),
  39. uint32(unsafe.Sizeof(info))); err != nil {
  40. _ = windows.CloseHandle(job)
  41. return err
  42. }
  43. if err := windows.AssignProcessToJobObject(job, windows.CurrentProcess()); err != nil {
  44. _ = windows.CloseHandle(job)
  45. return err
  46. }
  47. return nil
  48. }