fdusage_darwin.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // +build darwin
  17. package fdtrack
  18. import (
  19. "os"
  20. "syscall"
  21. "unsafe"
  22. )
  23. // #cgo CFLAGS: -lproc
  24. // #include <libproc.h>
  25. // #include <stdlib.h>
  26. import "C"
  27. func fdlimit() int {
  28. var nofile syscall.Rlimit
  29. if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &nofile); err != nil {
  30. return 0
  31. }
  32. return int(nofile.Cur)
  33. }
  34. func fdusage() (int, error) {
  35. pid := C.int(os.Getpid())
  36. // Query for a rough estimate on the amout of data that
  37. // proc_pidinfo will return.
  38. rlen, err := C.proc_pidinfo(pid, C.PROC_PIDLISTFDS, 0, nil, 0)
  39. if rlen <= 0 {
  40. return 0, err
  41. }
  42. // Load the list of file descriptors. We don't actually care about
  43. // the content, only about the size. Since the number of fds can
  44. // change while we're reading them, the loop enlarges the buffer
  45. // until proc_pidinfo says the result fitted.
  46. var buf unsafe.Pointer
  47. defer func() {
  48. if buf != nil {
  49. C.free(buf)
  50. }
  51. }()
  52. for buflen := rlen; ; buflen *= 2 {
  53. buf, err = C.reallocf(buf, C.size_t(buflen))
  54. if buf == nil {
  55. return 0, err
  56. }
  57. rlen, err = C.proc_pidinfo(pid, C.PROC_PIDLISTFDS, 0, buf, buflen)
  58. if rlen <= 0 {
  59. return 0, err
  60. } else if rlen == buflen {
  61. continue
  62. }
  63. return int(rlen / C.PROC_PIDLISTFD_SIZE), nil
  64. }
  65. panic("unreachable")
  66. }