rlimit_unix.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright (C) 2015 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. // +build !windows
  7. package osutil
  8. import (
  9. "runtime"
  10. "syscall"
  11. )
  12. const (
  13. darwinOpenMax = 10240
  14. )
  15. // MaximizeOpenFileLimit tries to set the resource limit RLIMIT_NOFILE (number
  16. // of open file descriptors) to the max (hard limit), if the current (soft
  17. // limit) is below the max. Returns the new (though possibly unchanged) limit,
  18. // or an error if it could not be changed.
  19. func MaximizeOpenFileLimit() (int, error) {
  20. // Get the current limit on number of open files.
  21. var lim syscall.Rlimit
  22. if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &lim); err != nil {
  23. return 0, err
  24. }
  25. // If we're already at max, there's no need to try to raise the limit.
  26. if lim.Cur >= lim.Max {
  27. return int(lim.Cur), nil
  28. }
  29. // macOS doesn't like a soft limit greater then OPEN_MAX
  30. // See also: man setrlimit
  31. if runtime.GOOS == "darwin" && lim.Max > darwinOpenMax {
  32. lim.Max = darwinOpenMax
  33. }
  34. // Try to increase the limit to the max.
  35. oldLimit := lim.Cur
  36. lim.Cur = lim.Max
  37. if err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &lim); err != nil {
  38. return int(oldLimit), err
  39. }
  40. // If the set succeeded, perform a new get to see what happened. We might
  41. // have gotten a value lower than the one in lim.Max, if lim.Max was
  42. // something that indicated "unlimited" (i.e. intmax).
  43. if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &lim); err != nil {
  44. // We don't really know the correct value here since Getrlimit
  45. // mysteriously failed after working once... Shouldn't ever happen, I
  46. // think.
  47. return 0, err
  48. }
  49. return int(lim.Cur), nil
  50. }