一、Qt 防止应用程序重复启动
通常我们的程序需要访问各种资源,如果同时起多份实例,造成资源争用,带来混乱。
因此需要一个方法保证任何时候只起一个实例。
在qt中可以借助共享内存来实现。
QSharedMemory有一个create方法,在qt帮助里这么描述:
bool QSharedMemory::create(int size, AccessMode mode = ReadWrite)
Creates a shared memory segment of size bytes with the key passed to the constructor, set with setKey() or set with setNativeKey(), then attaches to the new shared memory segment with the given access mode and returns true. If a shared memory segment identified by the key already exists, the attach operation is not performed and false is returned. When the return value is false, call error() to determine which error occurred.
example:
QApplication a(argc, argv);
QSharedMemory singleton(a.applicationName());
if(!singleton.create(1))
{
QMessageBox::warning(NULL, "Waring", "Program already running!");
return false;
}