本菜鸟不感高攀,想了几天,想到一个很本的办法,不正确的
方还请高手指点一下.
程序运行两个事例,每个实例互相监视另外的实例是否存在,
如果不存在,就运行一个.
代码:
// test_process.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "tchar.h"
#include "iostream.h"
#include "windows.h"
LPCTSTR lpszMutex1 = _T("mutex1");
LPCTSTR lpszMutex2 = _T("mutex2");
DWORD WINAPI Thread1(LPARAM lParam);
DWORD WINAPI Thread2(LPARAM lParam);
int main(int argc, char* argv[])
{
HANDLE hMutex1 = CreateMutex(NULL, FALSE, lpszMutex1);
if (hMutex1 != NULL)
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
CloseHandle(hMutex1);
cout << lpszMutex1 << " already exist." << endl;
HANDLE hMutex2 = CreateMutex(NULL, FALSE, lpszMutex2);
if (hMutex2 != NULL)
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
cout << lpszMutex2 << " already exist." << endl;
return 1;
}
}
DWORD dwThreadId;
HANDLE hThread = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)Thread1,NULL,0,&dwThreadId);
CloseHandle(hThread);
while (1)
Sleep(1);
return 0;
}
DWORD WINAPI Thread1(LPARAM lParam)
{
HANDLE hMutex;
while (1)
{
hMutex = OpenMutex(MUTEX_ALL_ACCESS, TRUE, lpszMutex1);
if (! hMutex)
{
STARTUPINFO si = { sizeof STARTUPINFO };
PROCESS_INFORMATION pi;
TCHAR szBuf[MAX_PATH];
GetModuleFileName(GetModuleHandle(NULL), szBuf, MAX_PATH);
CreateProcess(szBuf, NULL, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
CloseHandle(hMutex);
hMutex = OpenMutex(MUTEX_ALL_ACCESS, TRUE, lpszMutex2);
if (! hMutex)
{
cout << "mutex 2 created." << endl;
STARTUPINFO si = { sizeof STARTUPINFO };
PROCESS_INFORMATION pi;
TCHAR szBuf[MAX_PATH];
GetModuleFileName(GetModuleHandle(NULL), szBuf, MAX_PATH);
CreateProcess(szBuf, NULL, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
CloseHandle(hMutex);
cout << "Thread ..." << endl;
Sleep(1);
}
return 1;
}
延伸阅读
文章来源于领测软件测试网 https://www.ltesting.net/
关于领测软件测试网 | 领测软件测试网合作伙伴 | 广告服务 | 投稿指南 | 联系我们 | 网站地图 | 友情链接
版权所有(C) 2003-2010 TestAge(领测软件测试网)|领测国际科技(北京)有限公司|软件测试工程师培训网 All Rights Reserved
北京市海淀区中关村南大街9号北京理工科技大厦1402室 京ICP备10010545号-5
技术支持和业务联系:info@testage.com.cn 电话:010-51297073
版权所有(C) 2003-2010 TestAge(领测软件测试网)|领测国际科技(北京)有限公司|软件测试工程师培训网 All Rights Reserved
北京市海淀区中关村南大街9号北京理工科技大厦1402室 京ICP备10010545号-5
技术支持和业务联系:info@testage.com.cn 电话:010-51297073