sys_cloexec.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2013 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // This file implements sysSocket and accept for platforms that do not
  5. // provide a fast path for setting SetNonblock and CloseOnExec.
  6. // +build darwin dragonfly nacl netbsd openbsd solaris
  7. package net
  8. import "syscall"
  9. // Wrapper around the socket system call that marks the returned file
  10. // descriptor as nonblocking and close-on-exec.
  11. func sysSocket(family, sotype, proto int) (int, error) {
  12. // See ../syscall/exec_unix.go for description of ForkLock.
  13. syscall.ForkLock.RLock()
  14. s, err := syscall.Socket(family, sotype, proto)
  15. if err == nil {
  16. syscall.CloseOnExec(s)
  17. }
  18. syscall.ForkLock.RUnlock()
  19. if err != nil {
  20. return -1, err
  21. }
  22. if err = syscall.SetNonblock(s, true); err != nil {
  23. syscall.Close(s)
  24. return -1, err
  25. }
  26. return s, nil
  27. }
  28. // Wrapper around the accept system call that marks the returned file
  29. // descriptor as nonblocking and close-on-exec.
  30. func accept(s int) (int, syscall.Sockaddr, error) {
  31. // See ../syscall/exec_unix.go for description of ForkLock.
  32. // It is probably okay to hold the lock across syscall.Accept
  33. // because we have put fd.sysfd into non-blocking mode.
  34. // However, a call to the File method will put it back into
  35. // blocking mode. We can't take that risk, so no use of ForkLock here.
  36. ns, sa, err := syscall.Accept(s)
  37. if err == nil {
  38. syscall.CloseOnExec(ns)
  39. }
  40. if err != nil {
  41. return -1, nil, err
  42. }
  43. if err = syscall.SetNonblock(ns, true); err != nil {
  44. syscall.Close(ns)
  45. return -1, nil, err
  46. }
  47. return ns, sa, nil
  48. }