utils_unix.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // +build !windows
  2. package utils
  3. import (
  4. "io/ioutil"
  5. "os"
  6. "strconv"
  7. "golang.org/x/sys/unix"
  8. )
  9. func CloseExecFrom(minFd int) error {
  10. fdList, err := ioutil.ReadDir("/proc/self/fd")
  11. if err != nil {
  12. return err
  13. }
  14. for _, fi := range fdList {
  15. fd, err := strconv.Atoi(fi.Name())
  16. if err != nil {
  17. // ignore non-numeric file names
  18. continue
  19. }
  20. if fd < minFd {
  21. // ignore descriptors lower than our specified minimum
  22. continue
  23. }
  24. // intentionally ignore errors from unix.CloseOnExec
  25. unix.CloseOnExec(fd)
  26. // 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)
  27. }
  28. return nil
  29. }
  30. // NewSockPair returns a new unix socket pair
  31. func NewSockPair(name string) (parent *os.File, child *os.File, err error) {
  32. fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM|unix.SOCK_CLOEXEC, 0)
  33. if err != nil {
  34. return nil, nil, err
  35. }
  36. return os.NewFile(uintptr(fds[1]), name+"-p"), os.NewFile(uintptr(fds[0]), name+"-c"), nil
  37. }