ClickHouse/src/Common/getCurrentProcessFDCount.cpp

47 lines
1.1 KiB
C++
Raw Normal View History

2021-10-27 12:26:42 +00:00
#include <Common/getCurrentProcessFDCount.h>
#include <Common/ShellCommand.h>
#include <IO/WriteBufferFromString.h>
#include <unistd.h>
2021-11-12 12:48:42 +00:00
#include <fmt/format.h>
#include <IO/ReadHelpers.h>
2021-11-19 09:30:58 +00:00
#include <filesystem>
2021-10-27 12:26:42 +00:00
int getCurrentProcessFDCount()
{
2021-11-19 09:30:58 +00:00
namespace fs = std::filesystem;
2021-11-17 12:44:07 +00:00
int result = -1;
2021-10-27 12:26:42 +00:00
#if defined(__linux__) || defined(__APPLE__)
using namespace DB;
2021-11-12 12:48:42 +00:00
Int32 pid = getpid();
2021-10-27 12:26:42 +00:00
2021-11-19 09:30:58 +00:00
auto proc_fs_path = fmt::format("/proc/{}/fd", pid);
if (fs::exists(proc_fs_path))
{
result = std::distance(fs::directory_iterator(proc_fs_path), fs::directory_iterator{});
}
else if (fs::exists("/dev/fd"))
2021-11-12 12:48:42 +00:00
{
2021-11-19 09:30:58 +00:00
result = std::distance(fs::directory_iterator("/dev/fd"), fs::directory_iterator{});
2021-11-12 12:48:42 +00:00
}
2021-11-19 09:30:58 +00:00
else
2021-11-12 12:48:42 +00:00
{
/// Then try lsof command
String by_lsof = fmt::format("lsof -p {} | wc -l", pid);
2021-11-19 09:30:58 +00:00
auto command = ShellCommand::execute(by_lsof);
2021-11-12 12:48:42 +00:00
try
{
2021-11-17 12:44:07 +00:00
readIntText(result, command->out);
2021-11-12 12:48:42 +00:00
command->wait();
}
catch (...)
{
}
}
2021-11-19 09:30:58 +00:00
2021-10-27 12:26:42 +00:00
#endif
2021-11-17 12:44:07 +00:00
return result;
2021-10-27 12:26:42 +00:00
}