Single Instance application

Today, we are going to learn, how to create a application, which launch only a single instance on system.
1.create a system level object.
2. checking, is that object already exist or not.
  a. if not exist launch application.
  b. if exist check is that zombie process or alive
    i. if alive instance, don't launch new instance just prompt a message to user and exit.
    ii if zombie process, destroy the object and launch new instance of application.

I am providing sample code windows MFC application, here i used the mutex as system object.

This code should put in initinstance of winapp MFC class.
Based on this you can create a class and create a global object that class.
CString strTitle;
strTitle.LoadString( AFX_IDS_APP_TITLE );
HANDLE hmutex = OpenMutex( MUTEX_ALL_ACCESS, TRUE, strTitle );
if( hmutex!=NULL )
{
DWORD dwRet = WaitForSingleObject(hmutex,10);
If(dwRet!=WAIT_ABANDONED){
ReleaseMutex(hmutex);
}
else{
          AfxMessageBox( "App already exist", MB_OK | MB_ICONEXCLAMATION, (UINT)-1 );
return FALSE;
}
}
hmutex = CreateMutex( NULL, FALSE, strTitle );

you can use similar logic using pthread or boost thread to create application on linux, unix environments.
Thanks to reading this.

No comments:

Post a Comment

would you like it. :)