Is there a cross-platform solution in C++ for creating an unique process?
I 开发者_如何学编程need to make my program only one process on several platforms. I have known it can be solved with mutex on Windows, but I don't know how are other plat-forms like Linux. Mutex is not a part of C++ 03 standard though it is in C++ 0x standard. I have to wait a long time before compilers support C++ 0x well. Can boost's mutex be used for this?
Thanks in advance :)
Neither std::mutex nor boost::mutex expose the functionality of Win32 mutexes that is needed to make this work, namely system-global named mutexes, so no, you can't use either of them.
The easiest and most portable way is probably to simply create a lock file (you can write a PID to it, and then check if the process still exists to avoid locking the program out after abnormal termination). You still might need some platform-specific glue code, though.
Have a look at boost's interprocess library: http://www.boost.org/doc/libs/1_47_0/doc/html/interprocess.html
I have used a named_mutex http://www.boost.org/doc/libs/1_47_0/doc/html/boost/interprocess/named_mutex.html to make sure only one instance of my program was running.
I don't believe this can be done with a boost::mutex, but you can probably achieve the desired effect with the Boost Interprocess library.
精彩评论