Fix file descriptor leak. (#7704)

This commit is contained in:
Jiaming Yuan 2022-02-25 17:49:33 +08:00 committed by GitHub
parent 1b25dd59f9
commit 5eed2990ad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -2,10 +2,10 @@
* Copyright 2022 by XGBoost Contributors * Copyright 2022 by XGBoost Contributors
*/ */
#include "threading_utils.h" #include "threading_utils.h"
#if defined(__linux__)
#include <fcntl.h> #include <fstream>
#include <unistd.h> #include <string>
#endif // defined(__linux__)
#include "xgboost/logging.h" #include "xgboost/logging.h"
namespace xgboost { namespace xgboost {
@ -26,12 +26,12 @@ int32_t GetCfsCPUCount() noexcept {
// swap limt /sys/fs/cgroup/memory.memsw.limit_in_bytes // swap limt /sys/fs/cgroup/memory.memsw.limit_in_bytes
auto read_int = [](char const* const file_path) noexcept { auto read_int = [](char const* const file_path) noexcept {
auto const fd(::open(file_path, O_RDONLY, 0)); std::ifstream fin(file_path);
if (fd == -1) { if (!fin) {
return -1; return -1;
} }
char value[64]; std::string value;
CHECK(::read(fd, value, sizeof(value)) < signed(sizeof(value))); fin >> value;
try { try {
return std::stoi(value); return std::stoi(value);
} catch (std::exception const&) { } catch (std::exception const&) {