aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Common/getCurrentProcessFDCount.cpp
blob: 6217d92fbc173d6cc8091a84348c03b1526aaa9e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <Common/getCurrentProcessFDCount.h>
#include <Common/ShellCommand.h>
#include <IO/WriteBufferFromString.h>
#include <unistd.h>
#include <fmt/format.h>
#include <IO/ReadHelpers.h>
#include <filesystem>


Int64 getCurrentProcessFDCount()
{
    namespace fs = std::filesystem;
    Int64 result = -1;
#if defined(OS_LINUX)  || defined(OS_DARWIN)
    using namespace DB;

    Int32 pid = getpid();

    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"))
    {
        result = std::distance(fs::directory_iterator("/dev/fd"), fs::directory_iterator{});
    }
    else
    {
        /// Then try lsof command
        String by_lsof = fmt::format("lsof -p {} | wc -l", pid);
        auto command = ShellCommand::execute(by_lsof);

        try
        {
            readIntText(result, command->out);
            command->wait();
        }
        catch (...)
        {
        }
    }

#endif
    return result;
}