//test1.cpp
#include <windows.h>
DWORD WINAPI ThreadCheckProc(LPVOID lParam)
{
STARTUPINFO si={sizeof(si)};
PROCESS_INFORMATION pi={0};
HANDLE hMutex;
char *pName=(char *)lParam;
while(true)
{
hMutex=OpenMutex(MUTEX_ALL_ACCESS,FALSE,pName);
if(!hMutex)
{
CreateProcess(pName,
NULL,
NULL, // Process handle not inheritable.
NULL, // Thread handle not inheritable.
FALSE, // Set handle inheritance to FALSE.
0, // No creation flags.
NULL, // Use parent's environment block.
NULL, // Use parent's starting directory.
&si, // Pointer to STARTUPINFO structure.
&pi ); // Pointer to PROCESS_INFORMATION structure.
WaitForSingleObject( pi.hProcess, INFINITE );
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
else
{
CloseHandle(hMutex);
}
Sleep(1);
}
}
int WINAPI WinMain(
HINSTANCE hInstance, // handle to current instance
HINSTANCE hPrevInstance, // handle to previous instance
LPSTR lpCmdLine, // command line
int nCmdShow // show state
)
{
DWORD ThreadId;
CreateMutex(NULL,TRUE,"test1.exe");
CreateThread(NULL,0,ThreadCheckProc,(LPVOID *)"test2.exe",0,&ThreadId);
while(1)
{
Sleep(1000);
}
return 0;
}
//test2.cpp
#include <windows.h>
DWORD WINAPI ThreadCheckProc(LPVOID lParam)
{
STARTUPINFO si={sizeof(si)};
PROCESS_INFORMATION pi={0};
HANDLE hMutex;
char *pName=(char *)lParam;
while(true)
{
hMutex=OpenMutex(MUTEX_ALL_ACCESS,FALSE,pName);
if(!hMutex)
{
CreateProcess(pName,
NULL,
NULL, // Process handle not inheritable.
NULL, // Thread handle not inheritable.
FALSE, // Set handle inheritance to FALSE.
0, // No creation flags.
NULL, // Use parent's environment block.
NULL, // Use parent's starting directory.
&si, // Pointer to STARTUPINFO structure.
&pi ); // Pointer to PROCESS_INFORMATION structure.
WaitForSingleObject( pi.hProcess, INFINITE );
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
else
{
CloseHandle(hMutex);
}
Sleep(1);
}
}
int WINAPI WinMain(
HINSTANCE hInstance, // handle to current instance
HINSTANCE hPrevInstance, // handle to previous instance
LPSTR lpCmdLine, // command line
int nCmdShow // show state
)
{
DWORD ThreadId;
CreateMutex(NULL,TRUE,"test2.exe");
CreateThread(NULL,0,ThreadCheckProc,(LPVOID *)"test1.exe",0,&ThreadId);
while(1)
{
Sleep(1000);
}
return 0;
}