【小练习】C++实现双进程守护

// protectoion2.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <windows.h>

int _tmain(int argc, _TCHAR* argv[])
{
	HANDLE event1 = nullptr;
	HANDLE event2 = nullptr;
	STARTUPINFO si = { 0 };
	PROCESS_INFORMATION pi = { 0 };
	event2 = CreateEvent(NULL, FALSE, TRUE, L"Global\\p2");
	while (true)
	{
		if (!(event1 = OpenEvent(EVENT_MODIFY_STATE, FALSE, L"Global\\p1")))
		{
			if (!CreateProcess(L"protection1.exe", NULL, NULL, NULL, NULL, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi))
			{
				printf("打开守护进程失败!\n");
			}
			
			printf("打开守护进程成功!PID:%d \n", pi.dwProcessId);
			WaitForSingleObject(pi.hProcess, INFINITE);
			printf("守护进程被关闭!\n");
			CloseHandle(pi.hProcess);
			
		}
		CloseHandle(event1);
		Sleep(0);
	}

	return 0;
}

 

另一个进程

 

// protectoion1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <windows.h>

int _tmain(int argc, _TCHAR* argv[])
{
	HANDLE event1 = nullptr;
	STARTUPINFO si = { 0 };
	PROCESS_INFORMATION pi = { 0 };
	CreateEvent(NULL, FALSE, TRUE, L"Global\\p1");
	while (true)
	{
		if (!(event1 = OpenEvent(EVENT_MODIFY_STATE, FALSE, L"Global\\p2")))
		{
			if (!CreateProcess(L"protection2.exe", NULL, NULL, NULL, NULL, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi))
			{
				printf("打开守护进程失败!\n");
			}
			printf("打开守护进程成功!PID:%d \n",pi.dwProcessId);
			WaitForSingleObject(pi.hProcess, INFINITE);
			printf("守护进程被关闭!\n");
			CloseHandle(pi.hProcess);
		}
		CloseHandle(event1);
		Sleep(0);
	}

	return 0;
}

 

文 / luna
LEAVE A REPLY

loading