utils_unix.go 728 B

12345678910111213141516171819202122232425262728293031323334
  1. // +build !windows
  2. package utils
  3. import (
  4. "io/ioutil"
  5. "strconv"
  6. "syscall"
  7. )
  8. func CloseExecFrom(minFd int) error {
  9. fdList, err := ioutil.ReadDir("/proc/self/fd")
  10. if err != nil {
  11. return err
  12. }
  13. for _, fi := range fdList {
  14. fd, err := strconv.Atoi(fi.Name())
  15. if err != nil {
  16. // ignore non-numeric file names
  17. continue
  18. }
  19. if fd < minFd {
  20. // ignore descriptors lower than our specified minimum
  21. continue
  22. }
  23. // intentionally ignore errors from syscall.CloseOnExec
  24. syscall.CloseOnExec(fd)
  25. // the cases where this might fail are basically file descriptors that have already been closed (including and especially the one that was created when ioutil.ReadDir did the "opendir" syscall)
  26. }
  27. return nil
  28. }