ThreadSchedule 3.0.0
Modern C++ thread management library
Loading...
Searching...
No Matches
cgroup.hpp
Go to the documentation of this file.
1#pragma once
2
8#include "native_thread.hpp"
9
10#ifndef _WIN32
11# include <cerrno>
12# include <fcntl.h>
13# include <string>
14# include <system_error>
15# include <unistd.h>
16
18{
19
24inline auto
25cgroup_attach_tid(std::string const& cgroup_dir, native_thread_id tid) -> result<void>
26{
27 if (tid <= 0)
28 return unexpected(std::make_error_code(std::errc::invalid_argument));
29
30 char const* const candidates[] = { "cgroup.threads", "tasks" };
31 std::string const value = std::to_string(tid) + "\n";
32 for (auto const* file : candidates)
33 {
34 std::string const path = cgroup_dir + "/" + file;
35 int const descriptor = open(path.c_str(), O_WRONLY | O_CLOEXEC);
36 if (descriptor < 0)
37 continue;
38
39 std::size_t offset = 0;
40 while (offset < value.size())
41 {
42 auto const written = write(descriptor, value.data() + offset, value.size() - offset);
43 if (written > 0)
44 {
45 offset += static_cast<std::size_t>(written);
46 continue;
47 }
48 if (written < 0 && errno == EINTR)
49 continue;
50 break;
51 }
52 (void)close(descriptor);
53 if (offset == value.size())
54 return {};
55 }
56 return unexpected(std::make_error_code(std::errc::operation_not_permitted));
57}
58
59} // namespace threadschedule::advanced
60#endif
auto cgroup_attach_tid(std::string const &cgroup_dir, native_thread_id tid) -> result< void >
Attach a native Linux thread ID to a cgroup v1 or v2 directory.
Definition cgroup.hpp:25
Native thread identity and handle escape hatches.