简体   繁体   中英

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.

我不相信这可以通过boost :: mutex完成,但你可以通过Boost Interprocess库实现所需的效果。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM