开始使用CreatEvent停止的过程

时间:2019-06-17 09:58:31

标签: c++

我正在尝试编写一个程序来获取进程信息。我的程序使用createEvent检查是否停止了任何进程?如果该过程停止,程序将调用并重新启动它。     对于project1和project2是任意两个项目。我希望当程序运行时,如果两个项目之一停止,程序将回叫它们。

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

using namespace std;

HANDLE eventP1;
HANDLE eventP2;
HANDLE RunProcess(TCHAR* pszPath)
{
    PROCESS_INFORMATION procInf;
    STARTUPINFO startInf;
    memset(&procInf, 0, sizeof(procInf));
    memset(&startInf, 0, sizeof(startInf));

    BOOL result;
    result = CreateProcess(pszPath, NULL, NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &startInf, &procInf);
    if (result == FALSE)
    {
    cout << "Process creation failed!" << endl;
    return 0;
    }
    else
    {
    CloseHandle(procInf.hThread);
    return procInf.hProcess;
    }
}

int _tmain(int argc, _TCHAR* argv[])

{
HANDLE hEndEvents[2];
    DWORD dwRet;
    eventP1 = CreateEvent(NULL, TRUE, FALSE, _T("Global\\eventP1"));
    eventP2 = CreateEvent(NULL, TRUE, FALSE, _T("Global\\eventP2"));


    hEndEvents[0] = OpenEvent(EVENT_ALL_ACCESS, FALSE, _T("Global\\eventP1"));
    hEndEvents[1] = OpenEvent(EVENT_ALL_ACCESS, FALSE, _T("Global\\eventP2"));

    if (hEndEvents[0] == NULL || hEndEvents[1] == NULL)
    {
        cout << "Open Event " << endl;
        cout << GetLastError() << endl;

    }

    RunProcess(_T("D:\\Project_VuongDV\\VS2013\\DemoEventProcess\\Debug\\Project1.exe"));
    RunProcess(_T("D:\\Project_VuongDV\\VS2013\\DemoEventProcess\\Debug\\Project2.exe"));

    while (true)
    {
        dwRet = WaitForMultipleObjects(2, hEndEvents, FALSE, INFINITE);
        if (dwRet == WAIT_OBJECT_0 || dwRet == WAIT_OBJECT_0 + 1)
        {
            Sleep(100);
            ResetEvent(hEndEvents[0]);
            ResetEvent(hEndEvents[1]);
            cout << "project1 and Project2 run" << endl;
            SetEvent(hEndEvents[0]);
            SetEvent(hEndEvents[1]);


        }

        else
        {
            cout << "WAIL FALSE" << endl;
            cout << "Thread error is" << GetLastError() << endl;
            RunProcess(_T("D:\\Project_VuongDV\\VS2013\\DemoEventProcess\\Debug\\Project1.exe"));
            RunProcess(_T("D:\\Project_VuongDV\\VS2013\\DemoEventProcess\\Debug\\Project2.exe"));

        }

    }

    CloseHandle(hEndEvents[1]);
    CloseHandle(hEndEvents[2]);
    system("pause");
    return 0;
}

0 个答案:

没有答案