How to force my application to be single process by QsystemSemphore? Qt, Linux [duplicate]
Possible Duplicate:
How to force my application to open one exe only? qt, linux
Hi,
I want to force my application to open one exe only, how to do it by QsystemSemaphore? i.e. if the proce
10x!
I don't think thats easily solvable using a QSystemSemaphore. As far as I see, this class only supports blocking lock attempts. That seams to be the major point there: you can only call release(succeeds always but doesn't tell you anything) or acquire(which only tells you that you hit the limit by blocking you forever):
If a instance creates a semaphore it won't know if it really created it or if its using a existing one. If it's a binary semaphore at acquire two things might happen. Either it gets the lock, meaning its the first and only instance, or it just blocks there until the first instance quits.
To bypass that problem you might put that test into a separate thread, so you could check if it gets blocked using a external timeout at that thread, but honesty attempts like that are dirty and extreme risky, there is no way to get it working 100% safely that way too.
As you talk about a exe, might be assumed this could be solved windows platform-only?
//create a somewhat unique semaphore key, eg by hashing the application path
QString Key = QString("Local\\MyApp_%1").arg(qHash(QByteArray(argv[0])), 8, 16, QChar('0'));
HANDLE hMutex = CreateMutexW(NULL, FALSE, Key.utf16());
//NOTE: unlikely, but hMutex might be NULL, check for errors
//try to lock the mutex, but don't wait for it
if(WAIT_TIMEOUT == WaitForSingleObject(hMutex, 0))
{ //mutex is locked by another instance
//TODO: handle that somehow
return 0;
}
//TODO: place standard QT startup code here, for example
QApplication a(argc, argv);
QtMyApplication w;
w.show();
int iReturn = a.exec();
//release and close the mutex
ReleaseMutex(hMutex);
CloseHandle(hMutex);
return iReturn;
For more portable solutions something very similar can be done using a lock-file(open a temporary file for exclusive access, I think thats what QtSingleApplication does), but I personally don't like that file-based workaround.
精彩评论