fdlimit_unix.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2016 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 linux netbsd openbsd solaris
  17. package fdlimit
  18. import "syscall"
  19. // Raise tries to maximize the file descriptor allowance of this process
  20. // to the maximum hard-limit allowed by the OS.
  21. // Returns the size it was set to (may differ from the desired 'max')
  22. func Raise(max uint64) (uint64, error) {
  23. // Get the current limit
  24. var limit syscall.Rlimit
  25. if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {
  26. return 0, err
  27. }
  28. // Try to update the limit to the max allowance
  29. limit.Cur = limit.Max
  30. if limit.Cur > max {
  31. limit.Cur = max
  32. }
  33. if err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {
  34. return 0, err
  35. }
  36. // MacOS can silently apply further caps, so retrieve the actually set limit
  37. if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {
  38. return 0, err
  39. }
  40. return limit.Cur, nil
  41. }
  42. // Current retrieves the number of file descriptors allowed to be opened by this
  43. // process.
  44. func Current() (int, error) {
  45. var limit syscall.Rlimit
  46. if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {
  47. return 0, err
  48. }
  49. return int(limit.Cur), nil
  50. }
  51. // Maximum retrieves the maximum number of file descriptors this process is
  52. // allowed to request for itself.
  53. func Maximum() (int, error) {
  54. var limit syscall.Rlimit
  55. if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {
  56. return 0, err
  57. }
  58. return int(limit.Max), nil
  59. }