You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在现代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() (or QProcess::pid() for the current process) returns a qint64 containing the process ID, perfect if you’re already using Qt for your application.

Quick Notes

  • Platform-specific PID types (like pid_t on Unix or DWORD on Windows) can vary in size, so sticking to standard integer types like std::uintmax_t or std::int64_t in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:30:35