Liny_@NotePad

沉迷ACG中

【20090916】C++培训日记-使用内核对象使程序单实例运行

YOYO posted @ 2009年9月16日 23:29 in 【C/C++】 with tags 单实例 内核对象 , 2257 阅读

内核对象是所有Windows进程都可以访问的,因此可以使用其中的互斥信号量和事件对象使程序单实例运行。。

比起原来的IO锁好了很多 = = DEMO如下:

【使用互斥信号量(互斥对象)实现】

//////////////////////////////////////////////////////////////////////////
//	CopyRight(c) 2009, YOYO, All Rights Reserved.
//	Author: LIN YiQian
//	Created: 2009/09/16
//	Describe: 使用内核对象控制程序只能单实例 演示
//////////////////////////////////////////////////////////////////////////
#include <Windows.h>
#include <iostream>
using namespace std;

void main(void)
{
	HANDLE hInstance = CreateMutex(NULL, TRUE, "SingleInstance");

	if (hInstance)
	{
		if (ERROR_ALREADY_EXISTS == GetLastError())
		{
			printf("程序已经启动!");

			system("pause");
			return;
		}
	}
	
	while (true)
	{
		printf("程序运行阿 = = 运行阿 = = 运行阿。。\n");
		Sleep(100);
	}

	CloseHandle(hInstance);

	return;
}

【使用事件对象(事件信号量)实现】

//////////////////////////////////////////////////////////////////////////
//	CopyRight(c) 2009, YOYO, All Rights Reserved.
//	Author: LIN YiQian
//	Created: 2009/09/16
//	Describe: 使用事件对象控制单实例程序 演示
//////////////////////////////////////////////////////////////////////////
#include <Windows.h>
#include <iostream>
using namespace std;

void main(void)
{
	HANDLE hInstance = CreateEvent(NULL, FALSE, TRUE, "SingleInstance");

	if (hInstance)
	{
		if (ERROR_ALREADY_EXISTS == GetLastError())
		{
			printf("程序已经在运行!");

			system("pause");
			return;
		}
	}

	while (true)
	{
		printf("程序正在运行中。。运行中。。运行中。。= =\n");
		Sleep(100);
	}

	CloseHandle(hInstance);

	return;
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter