Merge pull request #45861 from thaJeztah/fileutils_deprecate_GetTotalUsedFds

pkg/fileutils: GetTotalUsedFds(): slight optimization for macOS
This commit is contained in:
Sebastiaan van Stijn 2023-07-11 20:06:24 +02:00 committed by GitHub
commit 6fee7c8f8b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,27 +1,25 @@
package fileutils // import "github.com/docker/docker/pkg/fileutils"
import (
"bytes"
"os"
"os/exec"
"strconv"
"strings"
)
// GetTotalUsedFds returns the number of used File Descriptors by
// executing `lsof -p PID`
// GetTotalUsedFds returns the number of used File Descriptors by executing
// "lsof -lnP -Ff -p PID".
//
// It uses the "-F" option to only print file-descriptors (f), and the "-l",
// "-n", and "-P" options to omit looking up user-names, host-names, and port-
// names. See [LSOF(8)].
//
// [LSOF(8)]: https://opensource.apple.com/source/lsof/lsof-49/lsof/lsof.man.auto.html
func GetTotalUsedFds() int {
pid := os.Getpid()
cmd := exec.Command("lsof", "-p", strconv.Itoa(pid))
output, err := cmd.CombinedOutput()
output, err := exec.Command("lsof", "-lnP", "-Ff", "-p", strconv.Itoa(os.Getpid())).CombinedOutput()
if err != nil {
return -1
}
outputStr := strings.TrimSpace(string(output))
fds := strings.Split(outputStr, "\n")
return len(fds) - 1
return bytes.Count(output, []byte("\nf")) // Count number of file descriptor fields in output.
}