What is a platform independent way of getting unique value of current instance (e.g. pid) in C++

2.2k views Asked by At

I would like to get a some kind (doesn't matter whether it's a process id or anything) of a unique integer value of current instance in C++ in a platform independent manner (that means no #if #else macro switch).

time based value would not be reliable since two instances can start at the same time.

Is there any way of achieving this?

EDIT: It doesn't have to be globally unique. it just needs to be unique system wide.

4

There are 4 answers

0
John Dibling On BEST ANSWER

Long story short, the answer is no, not without using platform-specific functionality.

[C++03]

The C++ language itself does not provide any mechanism to do this. In fact, C++ itself knows nothing about processes or interprocess communication. Without using platform-specific functionality -- either hand-rolled by you, which means #ifdefs, or in some cross-platform 3rd part library like Boost, which also means #ifdefs -- this cannot be done.

...and...

[C++11]

The C++ language has a basic concept of threads, but it provides no mechanism (that I can see) to create an interprocess communication mechanism, so the above still applies.

0
BЈовић On

This might be an overkill, but take a look into QUuid

2
Luchian Grigore On

Take a look at Boost process. Might be exactly what you're looking for. If you don't want to include the library, you can take a look at how the functionality is implemented.

0
masoud On

I think, you need Universally unique identifier