To ensure that only one instance is created for QT, The Global mutex variables and file lock methods are used for windows and linux respectively.
The Q_ OS _WIN32 macro is used to indicate that the target platform for compiling and running is windows, and Q_ OS _LINUX indicates that the target platform is linux.
# If defined Q_ OS _WIN32 // for win <br/> # include <windows. h> <br/> bool checkOnly () <br/> {<br/> // create a mutex <br/> HANDLE m_hMutex = CreateMutex (NULL, FALSE, L "fortest_abc123"); <br/> // check the error code <br/> if (GetLastError () = ERROR_ALREADY_EXISTS) {<br/> // If a mutex exists, release the handle and reset the mutex. <br/> CloseHandle (m_hMutex); <br/> m_hMutex = NULL; <br/> // exit the Program <br/> return false; <br/>}< br/> else <br/> return true; <br/>}< br/> # endif <br/> # if defined Q_ OS _LINUX // for linux <br/> # include <sys/types. h> <br/> # include <sys/stat. h> <br/> # include <fcntl. h> <br/> # include <unistd. h> <br/> bool checkOnly () <br/> {<br/> const char filename [] = "/tmp/lockfile "; <br/> int fd = open (filename, O_WRONLY | O_CREAT, 0644); <br/> int flock = lockf (fd, F_TLOCK, 0 ); <br/> if (fd =-1) {<br/> perror ("open lockfile/n"); <br/> return false; <br/>}< br/> // lock the file <br/> if (flock =-1) {<br/> perror ("lock file error/n"); <br/> return false; <br/>}< br/> // after the program exits, automatic File unlocking <br/> return true; <br/>}< br/> # endif <br/> int main (int argc, char * argv []) <br/>{< br/> QTextCodec: setCodecForLocale (QTextCodec: codecForName ("GB18030"); <br/> QTextCodec: setCodecForTr (QTextCodec :: codecForName ("GB18030"); <br/> Q_INIT_RESOURCE (wisdpsclient); <br/> QApplication app (argc, argv ); <br/> // check whether the program has been started <br/> if (checkOnly () = false) <br/> return 0; <br/> Test dialog; <br/> dialog. show (); <br/> return app.exe c (); <br/>}< br/>
Reference http://www.linuxsir.org/bbs/thread117349.html