开发者

How to check in C++ if an application is already running before launching a new instance?

开发者 https://www.devze.com 2023-03-20 20:43 出处:网络
I have found a few references to implementation but only one clear description in C++ (Joseph Newcomers article http://www.flounder.com/nomultiples.htm#CreateMutex), but it was (c)1999 so I was a litt

I have found a few references to implementation but only one clear description in C++ (Joseph Newcomers article http://www.flounder.com/nomultiples.htm#CreateMutex), but it was (c)1999 so I was a little reluctant to use it without first checking if there were "newe开发者_高级运维r/better" ways today.

Thanks


Any named object will do, can be a file, mutex, event, mailslot, TCP port, etc. ERROR_ALREADY_EXISTS tells you whether an instance already existed.

For objects in the Win32 kernel namespace, there is one change since 1999 -- because of terminal services, you now can use a prefix of Global\ or Local\ to specify whether it's one instance on the entire computer vs one per user logon session.

If you want something more portable, then binding a TCP port, or creating a file and exclusively locking it, tend to work well across a variety of OSes.


If you are programming on Windows, the standard way to do this is indeed to create a mutex at the start of your program. The mutex should live as long as the lifetime of your program and during this time, attempts to create a mutex with the same name will fail.


There hasn't been any significant improvement since then. For that matter, there hasn't been any significant improvement since a Usenet post I wrote a few years before that.

0

精彩评论

暂无评论...
验证码 换一张
取 消