如何在现代C++中以可移植、兼容标准的方式获取进程ID?
Great question! You’re totally right that standard C++ doesn’t have a native concept of processes—so there’s no direct, language-standard equivalent to std::this_thread::get_id() for process IDs. But we can build a portable solution that works across all modern platforms you’d care about, either by wrapping platform-specific system calls yourself or using established cross-platform libraries.
1. Manual Portable Wrapper (No External Dependencies)
If you want to avoid adding third-party libraries, the best approach is to wrap platform-specific system APIs using preprocessor directives. Here’s a clean implementation that returns the process ID as a standard integer type (to handle varying PID sizes across platforms):
#include <cstdint> // Platform-specific includes #ifdef _WIN32 #include <windows.h> #elif defined(__unix__) || defined(__unix) || defined(__APPLE__) #include <unistd.h> #endif std::uintmax_t get_process_id() { #ifdef _WIN32 // Windows uses GetCurrentProcessId() which returns a DWORD return static_cast<std::uintmax_t>(GetCurrentProcessId()); #else // Unix-like systems use getpid() which returns a pid_t return static_cast<std::uintmax_t>(getpid()); #endif }
- Why
std::uintmax_t? This type is guaranteed to be the largest unsigned integer type available, so it can hold any possible PID value from any platform without overflow. - The preprocessor checks cover Windows, Linux, macOS, BSD, and most other Unix-like systems you’ll encounter.
2. Using Cross-Platform Libraries (Less Boilerplate)
If you’re already using a cross-platform library in your project, many of them provide a ready-to-use, portable function for getting the process ID. This saves you from writing and maintaining the platform wrapper yourself:
- Boost.Process: Use
boost::this_process::get_id()(include<boost/process/process.hpp>) for a simple, portable call that returns the current process ID. - Abseil: The
absl::GetCurrentProcessId()function (include<absl/base/attributes.h>) abstracts away platform differences and returns a PID as a 64-bit integer. - Qt:
QCoreApplication::applicationPid()(orQProcess::pid()for the current process) returns aqint64containing the process ID, perfect if you’re already using Qt for your application.
Quick Notes
- Platform-specific PID types (like
pid_ton Unix orDWORDon Windows) can vary in size, so sticking to standard integer types likestd::uintmax_torstd::int64_tin your code’s public API ensures better portability. - As you pointed out, systems without a process concept almost never have thread support either, so this implementation will work everywhere
std::this_thread::get_id()is valid.
内容的提问来源于stack exchange,提问作者einpoklum

