In standard C++, we can get an id for the current execution thread: std::this_thread::get_id()
. But the language doesn't, at the time of writing, have an inherent notion of a process. I still want my process id, though.
So - what's the most portable, standards-friendly (albeit not language-standard) way to get the running process' ID in modern C++?
Notes:
C is a portable programming language If you write a C code in your machine, it will run on any machine which supports C, without modifying a single line of code. Because it is not tied to any hardware or system. We can say, it is a hardware independent language or platform independent language.
C compilers generate machine code which is portable only to a very limited extent, between machines of the same processor/memory architecture and OS.
The most obvious problem with writing portable C is that the size of various types changes between platforms. C defines five integer types, in signed and unsigned variants: char, short, int, long, and long long. On the system where I first learned C, these were 8, 16, 16, 32, and nonexistent, respectively.
Boost.Interprocess has boost::interprocess::ipcdetail::get_current_process_id.
The ACE library provides various OS-related functions and has been ported to many platforms. See here for a list. The library's ACE_OS namespace provides a getpid implementation.
In general, there's no universal way to get the process ID on every platform since that aspect of the OS's process management is outside the scope of the C++ language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With