Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain the process id portably in C++?

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:

  • I realize some machines don't have processes, but then, they don't necessarily have threads either... so there's no reason why a cross-platform function with a fallback for degenerate cases should not exist.
  • I'll want an actual process ID at least for POSIX-compliant OSes and Windows.
like image 591
einpoklum Avatar asked Apr 29 '18 13:04

einpoklum


People also ask

What is portable C code?

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.

Is compiled C code portable?

C compilers generate machine code which is portable only to a very limited extent, between machines of the same processor/memory architecture and OS.

What are portable data types in C?

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.


1 Answers

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.

like image 162
jspcal Avatar answered Sep 27 '22 23:09

jspcal