I am developing an application in QT for Windows and I have the following problem: 1. Some users are opening multiple instances of the same application, which is not allowed. How can I control that each user only opens the application once, without using qtsingleapplication?
Asked
Active
Viewed 264 times
0
-
3Why not use what QT provides for that? – Basile Starynkevitch Jun 01 '17 at 20:07
-
You can't prevent someone from opening your application more than once, but you can set up a named resource (mutex, shared memory, named pipe, etc.) and immediately exit your application if this resource is in use. – MrEricSir Jun 01 '17 at 21:05
-
I dont have any ideia how to implement that. – Eduardo Schettini Guimarães Jun 05 '17 at 15:20
1 Answers
0
A quick and a dirty way to do it would be to create a lock file. If the lock file exists and the process is active, the new instance will quit. A crude and unchecked example is given below.
bool isProcessRunning( DWORD processID, std::string processName) {
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
// Get a handle to the process.
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID );
// Get the process name.
if ( NULL != hProcess ) {
HMODULE hMod;
DWORD cbNeeded;
if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded) )
GetModuleBaseName( hProcess, hMod, szProcessName, sizeof(szProcessName)/sizeof(TCHAR) );
}
// Compare process name with your string
bool matchFound = !_tcscmp(szProcessName, processName.c_str() );
// Release the handle to the process.
CloseHandle( hProcess );
return matchFound;
};
void lockApp() {
/*
*
* lockApp() -> None
*
* Lock app to one instance
*
* @return None
*
*/
/* Flags */
int pid = -1;
bool procRunning = true;
/* App Lock file: Name and Location */
QString lockFile = QDir::temp().filePath( "MyAppName.lock" );
// check for the lock file and see if its stale.
if ( QFileInfo( lockFile ).exists() ) {
// OK, lock exists. Now, check if it is stale!
QFile pidFile( lockFile );
pidFile.open( QFile::ReadOnly );
pid = pidFile.readAll().toInt();
pidFile.close();
// if /proc/pid doesnot exist, we have a stale lock
if( isProcessRunning( pid, "MyAppName" ) ) {
procRunning = false;
QFile::remove( lockFile );
}
}
else {
procRunning = false;
}
if ( procRunning ) {
qApp->quit();
exit( 0 );
}
QFile pidFile( lockFile );
pidFile.open( QFile::WriteOnly );
pidFile.write( qPrintable( QString::number( qApp->applicationPid() ) ) );
pidFile.close();
};
The first function was taken from here. https://stackoverflow.com/a/13635127/1233513

Marcus
- 1,685
- 1
- 18
- 33