VLink  2.3.0
A high-performance communication middleware
utils.h
浏览该文件的文档.
1 /*
2  * Copyright (C) 2026 by Thun Lu. All rights reserved.
3  * Author: Thun Lu <thun.lu@zohomail.cn>
4  * Repo: https://github.com/thun-res/vlink
5  * _ __ __ _ __
6  * | | / / / / (_) ____ / /__
7  * | | / / / / / / / __ \ / //_/
8  * | |/ / / /___ / / / / / / / ,<
9  * |___/ /_____/ /_/ /_/ /_/ /_/|_|
10  *
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  * http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  */
23 
24 /**
25  * @file utils.h
26  * @brief Portable host-system utility surface used across the VLink runtime.
27  *
28  * @details
29  * @c vlink::Utils gathers free functions that paper over differences between Linux, macOS,
30  * Windows, QNX and Android. All public entry points are @c noexcept and report failure
31  * via empty strings, @c false return values or sentinel values such as @c pid @c == @c -1.
32  *
33  * Helper categories provided by the namespace:
34  *
35  * | Category | Representative entry points |
36  * | ---------------------- | ----------------------------------------------------------------- |
37  * | Process introspection | @c get_pid, @c get_process_start_time, @c is_terminating |
38  * | Host identity | @c get_host_name, @c get_machine_id, @c get_timezone_diff |
39  * | Filesystem helpers | @c get_tmp_dir, @c wait_for_device |
40  * | Environment management | @c get_env, @c set_env, @c unset_env |
41  * | Network discovery | @c get_all_ipv4_address, @c get_dds_default_address |
42  * | Thread control | @c set_thread_name, @c set_thread_priority, @c set_thread_stick |
43  * | Signal handling | @c register_terminate_signal, @c register_crash_signal |
44  * | Input/terminal | @c start_detect_keyboard, @c get_terminal_size |
45  * | System metrics | @c get_cpu_usage, @c get_memory_usage, @c is_process_running |
46  * | Memory hints | @c try_release_sys_memory |
47  * | Low-level primitives | @c yield_cpu |
48  *
49  * @note
50  * - @c yield_cpu() is inlined to emit the optimal idle hint per ISA: @c PAUSE on x86,
51  * @c YIELD on ARM, an explicit fence on RISC-V, otherwise @c std::this_thread::yield().
52  *
53  * @par Example
54  * @code
55  * vlink::Utils::set_thread_name("worker");
56  * vlink::Utils::set_thread_stick(0b11);
57  *
58  * vlink::Utils::register_terminate_signal([](int sig) {
59  * (void)sig;
60  * shutdown_application();
61  * });
62  * @endcode
63  */
64 
65 #pragma once
66 
67 #include <string>
68 #include <thread>
69 #include <utility>
70 #include <vector>
71 
72 #include "./functional.h"
73 #include "./macros.h"
74 
75 #ifdef _MSC_VER
76 extern "C" void _mm_pause(void);
77 #endif
78 
79 namespace vlink {
80 
81 /**
82  * @namespace vlink::Utils
83  * @brief Portable host-system utility functions.
84  */
85 namespace Utils { // NOLINT(readability-identifier-naming)
86 
87 /**
88  * @brief Returns the absolute path of the executable that is currently running.
89  *
90  * @return Full filesystem path, or an empty string when the OS query fails.
91  */
92 [[nodiscard]] VLINK_EXPORT std::string get_app_path() noexcept;
93 
94 /**
95  * @brief Returns the directory portion of the executable's absolute path.
96  *
97  * @return Directory without a trailing separator, or an empty string on failure.
98  */
99 [[nodiscard]] VLINK_EXPORT std::string get_app_dir() noexcept;
100 
101 /**
102  * @brief Returns the file-name portion of the executable's absolute path.
103  *
104  * @return Executable name, or an empty string on failure.
105  */
106 [[nodiscard]] VLINK_EXPORT std::string get_app_name() noexcept;
107 
108 /**
109  * @brief Returns the local machine's host name as reported by the operating system.
110  *
111  * @return Host name string, or an empty string on failure.
112  */
113 [[nodiscard]] VLINK_EXPORT std::string get_host_name() noexcept;
114 
115 /**
116  * @brief Returns the process identifier of the calling process.
117  *
118  * @return PID, or @c -1 on failure.
119  */
120 [[nodiscard]] VLINK_EXPORT int32_t get_pid() noexcept;
121 
122 /**
123  * @brief Returns the process identifier of the calling process as a decimal string.
124  *
125  * @return PID string, or an empty string on failure.
126  */
127 [[nodiscard]] VLINK_EXPORT std::string get_pid_str() noexcept;
128 
129 /**
130  * @brief Start time reported when a process exists but its start time cannot be read.
131  */
132 inline constexpr uint64_t kUnknownProcessStartTime = ~static_cast<uint64_t>(0);
133 
134 /**
135  * @brief Returns the kernel start time of a live process.
136  *
137  * @details
138  * Unit and epoch are platform-defined. Compare the value only for equality against another
139  * sample for the same PID; a mismatch means the PID was reused by a different process. Zombie
140  * and exited processes report as absent. A process that exists but denies inspection, for
141  * example another user's process under a restricted @c /proc, reports
142  * @c kUnknownProcessStartTime so callers never mistake it for a dead one.
143  *
144  * @param pid Process identifier.
145  *
146  * @return Start time, @c 0 when no such live process exists, or @c kUnknownProcessStartTime.
147  */
148 [[nodiscard]] VLINK_EXPORT uint64_t get_process_start_time(int32_t pid) noexcept;
149 
150 /**
151  * @brief Returns a path suitable for short-lived temporary files.
152  *
153  * @details
154  * Honours the @c VLINK_TMP_DIR environment override. Otherwise falls back to
155  * @c std::filesystem::temp_directory_path(), or @c /var/log on QNX.
156  *
157  * @return Temporary directory path.
158  */
159 [[nodiscard]] VLINK_EXPORT std::string get_tmp_dir() noexcept;
160 
161 /**
162  * @brief Reads the current value of an environment variable.
163  *
164  * @param key Variable name.
165  * @param default_value Value returned when @p key is not set. Default: empty string.
166  * @return Variable value, or @p default_value when unset.
167  */
168 [[nodiscard]] VLINK_EXPORT std::string get_env(const std::string& key, const std::string& default_value = "") noexcept;
169 
170 /**
171  * @brief Sets or updates an environment variable.
172  *
173  * @param key Variable name.
174  * @param value Variable value.
175  * @param force When @c true (default), overwrites an existing variable.
176  * @return @c true on success.
177  */
178 VLINK_EXPORT bool set_env(const std::string& key, const std::string& value, bool force = true) noexcept;
179 
180 /**
181  * @brief Removes an environment variable.
182  *
183  * @param key Variable name.
184  * @return @c true on success.
185  */
186 VLINK_EXPORT bool unset_env(const std::string& key) noexcept;
187 
188 /**
189  * @brief Returns whether an interface name is treated as virtual/tunnel-only by address discovery.
190  *
191  * @details Used by @c get_all_ipv4_address(true) and @c get_all_ipv6_address(true) to skip
192  * container, VPN, bridge and tunnel adapters when choosing transport discovery addresses.
193  *
194  * @param name Interface name; @c nullptr is treated as ignored.
195  * @return @c true when the name should be filtered out.
196  */
197 [[nodiscard]] VLINK_EXPORT bool is_ignored_iface_name(const char* name) noexcept;
198 
199 /**
200  * @brief Compares IPv4 or IPv6 literals numerically, with IPv4 ordered before IPv6.
201  *
202  * @param lhs Valid IP literal without a scope ID or prefix length.
203  * @param rhs Valid IP literal without a scope ID or prefix length.
204  * @return Whether @p lhs precedes @p rhs; equivalent IPv6 spellings compare equal.
205  */
206 [[nodiscard]] VLINK_EXPORT bool ip_less(const std::string& lhs, const std::string& rhs) noexcept;
207 
208 /**
209  * @brief Returns every IPv4 address bound to a local network interface.
210  *
211  * @param filter_available When @c true, only includes interfaces in the UP state. Default: @c false.
212  * @return Vector of dotted-decimal strings.
213  */
214 [[nodiscard]] VLINK_EXPORT std::vector<std::string> get_all_ipv4_address(bool filter_available = false) noexcept;
215 
216 /**
217  * @brief Returns every IPv6 address bound to a local network interface.
218  *
219  * @param filter_available When @c true, only includes interfaces in the UP state. Default: @c false.
220  * @return Vector of IPv6 strings.
221  */
222 [[nodiscard]] VLINK_EXPORT std::vector<std::string> get_all_ipv6_address(bool filter_available = false) noexcept;
223 
224 /**
225  * @brief Returns the interface name that owns a given IPv4 address.
226  *
227  * @param ipv4 Address to look up.
228  * @return Interface name, or an empty string when no match exists.
229  */
230 [[nodiscard]] VLINK_EXPORT std::string get_interface_name_by_ipv4(const std::string& ipv4) noexcept;
231 
232 /**
233  * @brief Returns the interface name that owns a given IPv6 address.
234  *
235  * @param ipv6 Address to look up.
236  * @return Interface name, or an empty string when no match exists.
237  */
238 [[nodiscard]] VLINK_EXPORT std::string get_interface_name_by_ipv6(const std::string& ipv6) noexcept;
239 
240 /**
241  * @brief Selects IPv4 addresses suitable as DDS participant unicast locators.
242  *
243  * @details
244  * When @c 127.0.0.1 is present it is placed first in the result; the remaining
245  * non-loopback unicast addresses are then appended until @c max_count is reached.
246  * Loopback is therefore included (as the leading entry) rather than filtered out.
247  *
248  * @param filter_available When @c true, only includes UP interfaces. Default: @c false.
249  * @param max_count Upper bound on the number of returned addresses. Nonpositive returns empty. Default: @c 5.
250  * @return Vector of selected IPv4 strings.
251  */
252 [[nodiscard]] VLINK_EXPORT std::vector<std::string> get_dds_default_address(bool filter_available = false,
253  int max_count = 5) noexcept;
254 
255 /**
256  * @brief Provides a singleton mutual-exclusion check for a program name.
257  *
258  * @details
259  * Uses a Win32 mutex on Windows and a POSIX lock file under @c VLINK_LOCK_DIR (or the
260  * platform default) elsewhere. Returns @c false when another instance already holds
261  * the lock.
262  *
263  * @param program_name Program tag used to build the lock identity. Empty defaults to the executable name.
264  * @return @c true when this process holds the singleton lock.
265  */
266 [[nodiscard]] VLINK_EXPORT bool check_singleton(const std::string& program_name = "") noexcept;
267 
268 /**
269  * @brief Polls a filesystem path until it exists or a timeout expires.
270  *
271  * @details
272  * Useful for waiting for device nodes (e.g. @c /dev/video0) at startup.
273  *
274  * @param path Filesystem path to poll.
275  * @param timeout_ms Maximum total wait in milliseconds.
276  * @param poll_ms Polling interval in milliseconds. Default: @c 50.
277  * @return @c true when the path appears within the timeout.
278  */
279 VLINK_EXPORT bool wait_for_device(const std::string& path, int timeout_ms, int poll_ms = 50) noexcept;
280 
281 /**
282  * @brief Emits the most efficient CPU pause/yield hint for the host ISA.
283  *
284  * @details
285  * Maps to @c PAUSE on x86, @c YIELD on ARMv7/AArch64, an explicit fence on RISC-V, and
286  * @c std::this_thread::yield() as a portable fallback. Always inlined.
287  */
288 VLINK_EXPORT void yield_cpu() noexcept;
289 
290 /**
291  * @brief Sets the Windows console output code page to UTF-8.
292  *
293  * @details
294  * Calls @c SetConsoleOutputCP(CP_UTF8); a no-op on non-Windows targets.
295  */
297 
298 /**
299  * @brief Sets the OS-visible name of a thread so debug tools display it.
300  *
301  * @param name Thread name; Linux truncates beyond 15 characters.
302  * @param thread Thread to rename, or @c nullptr for the calling thread. Default: @c nullptr.
303  * @return @c true on success.
304  */
305 VLINK_EXPORT bool set_thread_name(const std::string& name, std::thread* thread = nullptr) noexcept;
306 
307 /**
308  * @brief Updates the scheduling policy and priority of a thread.
309  *
310  * @details
311  * On Linux wraps @c pthread_setschedparam. Real-time policies require @c CAP_SYS_NICE
312  * or an adequate @c RLIMIT_RTPRIO. POSIX policy constants (@c SCHED_FIFO, @c SCHED_RR,
313  * @c SCHED_OTHER) come from @c <sched.h>, which callers must include. On Windows the
314  * value is mapped to a thread priority class or silently ignored.
315  *
316  * @param priority_level Policy-dependent priority value.
317  * @param policy Scheduling policy; @c -1 leaves the existing policy untouched.
318  * @param thread Thread to configure, or @c nullptr for the calling thread. Default: @c nullptr.
319  * @return @c true on success.
320  */
321 VLINK_EXPORT bool set_thread_priority(int priority_level, int policy = -1, std::thread* thread = nullptr) noexcept;
322 
323 /**
324  * @brief Pins a thread to a set of CPU cores expressed as a bitmask.
325  *
326  * @details
327  * Bit @c i of @p core_mask corresponds to core @c i, so @c 0b0101 pins to cores @c 0 and
328  * @c 2. Wraps @c pthread_setaffinity_np on Linux.
329  *
330  * @param core_mask Bitmask of CPU cores.
331  * @param thread Thread to pin, or @c nullptr for the calling thread. Default: @c nullptr.
332  * @return @c true on success.
333  */
334 VLINK_EXPORT bool set_thread_stick(uint32_t core_mask, std::thread* thread = nullptr) noexcept;
335 
336 /**
337  * @brief Returns the native OS thread identifier of the calling thread.
338  *
339  * @details
340  * Maps to:
341  * - Linux / Android / QNX: @c syscall(SYS_gettid) — kernel TID matching @c top / @c perf.
342  * - macOS / iOS: @c pthread_threadid_np() — 64-bit Mach thread id.
343  * - Windows: @c GetCurrentThreadId() — Win32 thread id.
344  *
345  * @return Native thread identifier.
346  */
347 [[nodiscard]] VLINK_EXPORT uint64_t get_native_thread_id() noexcept;
348 
349 /**
350  * @brief Reports whether the process has entered its final termination phase.
351  *
352  * @details
353  * On Windows this returns @c true once @c ExitProcess has terminated all other threads and
354  * process-detach callbacks are running; locks held by those threads are never released, so
355  * cross-thread cleanup must be skipped. Executable static destruction during a normal @c exit()
356  * and explicit @c FreeLibrary unloads report @c false. Other platforms always return @c false.
357  *
358  * @return @c true during terminal process shutdown on Windows.
359  */
360 [[nodiscard]] VLINK_EXPORT bool is_terminating() noexcept;
361 
362 /**
363  * @brief Installs a callback for graceful termination signals.
364  *
365  * @details
366  * Hooks @c SIGINT, @c SIGTERM and @c SIGHUP on POSIX, or @c SIGINT / @c SIGTERM on Windows.
367  * An empty @p callback restores the default disposition of these signals.
368  *
369  * @param callback Callback receiving the signal number.
370  * @param is_async When @c true, runs the callback on a dedicated thread instead of the
371  * signal context. Default: @c false.
372  * @param pass_through When @c true, re-raises the signal after the callback returns so the
373  * default OS behaviour also fires. Default: @c false.
374  */
375 VLINK_EXPORT void register_terminate_signal(MoveFunction<void(int)>&& callback, bool is_async = false,
376  bool pass_through = false) noexcept;
377 
378 /**
379  * @brief Installs a callback for crash signals such as @c SIGSEGV, @c SIGABRT, @c SIGFPE, @c SIGBUS.
380  *
381  * @details
382  * Useful for emitting crash diagnostics. The callback should be async-signal-safe and
383  * short. It runs at most once; on POSIX the signal is then re-raised with its default
384  * disposition so the process terminates with the original cause.
385  *
386  * @param callback Callback receiving the signal number.
387  */
388 VLINK_EXPORT void register_crash_signal(MoveFunction<void(int)>&& callback) noexcept;
389 
390 /**
391  * @brief Starts a background poller that detects keyboard input on stdin.
392  *
393  * @details
394  * Calls @p callback with a key name string (such as @c "enter" or @c "q") whenever a
395  * key is detected. Stop with @c stop_detect_keyboard().
396  *
397  * @param callback Callback receiving the key name. Default: @c nullptr (ignore events).
398  * @param poll_ms Polling interval in milliseconds. Default: @c 20.
399  */
400 VLINK_EXPORT void start_detect_keyboard(MoveFunction<void(const std::string& key)>&& callback = nullptr,
401  int poll_ms = 20) noexcept;
402 
403 /**
404  * @brief Stops the keyboard poller started by @c start_detect_keyboard().
405  *
406  * @details
407  * May be called from its keyboard callback to request exit. Calls from other threads
408  * wait for the poller to finish; starting it again also joins any previously stopped poller.
409  */
411 
412 /**
413  * @brief Returns the current terminal dimensions in columns and rows.
414  *
415  * @return Pair @c {columns, @c rows}; @c {-1, @c -1} when stdout is not a TTY.
416  */
417 [[nodiscard]] VLINK_EXPORT std::pair<int, int> get_terminal_size() noexcept;
418 
419 /**
420  * @brief Returns the system-wide CPU usage as a percentage averaged over all logical CPUs.
421  *
422  * @details
423  * Implemented as @c (1 @c - @c idle_delta @c / @c total_delta) @c * @c 100 from
424  * @c /proc/stat on Linux/Android or @c GetSystemTimes on Windows. Because the previous
425  * sample is zero-initialised, the first call after process start reports the average usage
426  * since boot rather than the usage over an interval.
427  *
428  * @return Percentage in @c [0.0, @c 100.0], or @c -1.0 on error / unsupported platform.
429  */
430 [[nodiscard]] VLINK_EXPORT double get_cpu_usage() noexcept;
431 
432 /**
433  * @brief Returns the system-wide memory usage as a percentage of total physical RAM.
434  *
435  * @return Percentage in @c [0.0, @c 100.0], or @c -1.0 on error / unsupported platform.
436  */
437 [[nodiscard]] VLINK_EXPORT double get_memory_usage() noexcept;
438 
439 /**
440  * @brief Reports whether at least one process with the given executable name is alive.
441  *
442  * @param process_name Executable name without a path component.
443  * @return @c true when a matching process exists.
444  */
445 [[nodiscard]] VLINK_EXPORT bool is_process_running(const std::string& process_name) noexcept;
446 
447 /**
448  * @brief Returns the local timezone offset from UTC in minutes.
449  *
450  * @details
451  * UTC+8 returns @c 480; UTC-5 returns @c -300.
452  *
453  * @return Offset in minutes.
454  */
455 [[nodiscard]] VLINK_EXPORT int32_t get_timezone_diff() noexcept;
456 
457 /**
458  * @brief Returns a stable identifier for the host machine.
459  *
460  * @details
461  * Reads @c /etc/machine-id on Linux and uses platform-specific equivalents elsewhere.
462  *
463  * @return Machine ID string, or an empty string on failure.
464  */
465 [[nodiscard]] VLINK_EXPORT std::string get_machine_id() noexcept;
466 
467 /**
468  * @brief Hints to the OS that any unreferenced cached memory pages can be released.
469  *
470  * @details
471  * On Linux invokes @c malloc_trim(0); on other platforms it is a no-op.
472  */
474 
475 ////////////////////////////////////////////////////////////////
476 /// Details
477 ////////////////////////////////////////////////////////////////
478 
479 #if defined(__GNUC__) && !defined(_WIN32) && !defined(__CYGWIN__)
480 inline __attribute__((artificial)) void yield_cpu() noexcept {
481 #else
482 inline void yield_cpu() noexcept {
483 #endif
484 #if __has_builtin(__yield)
485  __yield();
486 #elif defined(_MSC_VER) && defined(_YIELD_PROCESSOR)
487  _YIELD_PROCESSOR();
488 #elif __has_builtin(__builtin_ia32_pause)
489 __builtin_ia32_pause();
490 #elif defined(__x86_64__) || defined(_M_X64) || defined(__i386) || defined(_M_IX86)
491 #if defined(_MSC_VER)
492 _mm_pause();
493 #elif defined(__GNUC__)
494 __builtin_ia32_pause();
495 #else
496 __asm__("pause");
497 #endif
498 #elif __has_builtin(__builtin_arm_yield)
499 __builtin_arm_yield();
500 #elif defined(__arm__) || defined(__aarch64__)
501 #if defined(__GNUC__)
502 __asm__("yield");
503 #else
504 std::this_thread::yield();
505 #endif
506 #elif defined(__riscv)
507 __asm__(".word 0x0100000f");
508 #elif defined(_MSC_VER) && defined(_YIELD_PROCESSOR)
509 _YIELD_PROCESSOR();
510 #else
511 std::this_thread::yield();
512 #endif
513 }
514 
515 } // namespace Utils
516 
517 } // namespace vlink
Pool-backed type-erased callables: copyable vlink::Function and move-only vlink::MoveFunction.
Cross-platform macros for visibility, branch hints, copy prevention, singletons and string helpers.
#define VLINK_EXPORT
Definition: macros.h:81