rlimit_unix.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 "syscall"
  9. // MaximizeOpenFileLimit tries to set the resource limit RLIMIT_NOFILE (number
  10. // of open file descriptors) to the max (hard limit), if the current (soft
  11. // limit) is below the max. Returns the new (though possibly unchanged) limit,
  12. // or an error if it could not be changed.
  13. func MaximizeOpenFileLimit() (int, error) {
  14. // Get the current limit on number of open files.
  15. var lim syscall.Rlimit
  16. if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &lim); err != nil {
  17. return 0, err
  18. }
  19. // If we're already at max, there's no need to try to raise the limit.
  20. if lim.Cur >= lim.Max {
  21. return int(lim.Cur), nil
  22. }
  23. // Try to increase the limit to the max.
  24. oldLimit := lim.Cur
  25. lim.Cur = lim.Max
  26. if err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &lim); err != nil {
  27. return int(oldLimit), err
  28. }
  29. // If the set succeeded, perform a new get to see what happened. We might
  30. // have gotten a value lower than the one in lim.Max, if lim.Max was
  31. // something that indicated "unlimited" (i.e. intmax).
  32. if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &lim); err != nil {
  33. // We don't really know the correct value here since Getrlimit
  34. // mysteriously failed after working once... Shouldn't ever happen, I
  35. // think.
  36. return 0, err
  37. }
  38. return int(lim.Cur), nil
  39. }