win32程序中監測父進程是否退出的實現

一、在main函數中開闢一個監測線程: 函數

    HANDLE exit_thread;
    exit_thread = CreateThread(NULL, 0, run, NULL, 0, NULL); spa

二、在線程處理函數run中進行處理,若是父進程退出,則本程序也退出: 線程

  基本步驟以下: orm

(1)先獲取本身的進程ID,GetCurrentProcessID()
進程

(2) 獲取進程查詢句柄,調用OpenProcess()帶上PROCESS_QUERY_INFORMATION標誌
it

(3)調用NtQueryInformationProcess()來查詢進程信息
io

(4) 獲取父進程句柄,仍是調用OpenProcess()
form

(5) 啓動一個線程去等待父進程退出,WaitForSingleObject(ParentHandle, INFINITE)大功告成,這樣不管是父進程正常退出,仍是異常終止,子進程都能被退出。 thread

struct ProcessBasicInformation {
    LONG ExitStatus;
    PVOID PebBaseAddress;
    ULONG_PTR AffinityMask;
    LONG BasePriority;
    ULONG_PTR UniqueProcessId;
    ULONG_PTR InheritedFromUniqueProcessId;
};

typedef LONG(__stdcall *FPTR_NtQueryInformationProcess) (HANDLE, ULONG, PVOID, ULONG, PULONG);

unsigned long GetParentPid()
{
    ULONG_PTR ppid = 0;
    DWORD pid = GetCurrentProcessId();
    HANDLE hcurrent = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
    
    if (hcurrent)
    {
        FPTR_NtQueryInformationProcess NtQueryInformationProcess = (FPTR_NtQueryInformationProcess)GetProcAddress(GetModuleHandle("ntdll.dll"),
            "NtQueryInformationProcess");

        if (NtQueryInformationProcess != NULL)
        {
            ProcessBasicInformation pbi;
            if (NtQueryInformationProcess(hcurrent, 0, (void*)&pbi, sizeof(pbi), NULL) == 0)
            {
                ppid = pbi.InheritedFromUniqueProcessId;
            }
        }
        CloseHandle(hcurrent);
    }

    return ppid;
}

DWORD WINAPI run(LPVOID  lpparameter)
{
    ULONG_PTR pPid = GetParentPid();

    HANDLE pHandle = OpenProcess(PROCESS_QUERY_INFORMATION | SYNCHRONIZE, FALSE, pPid);

    if (WaitForSingleObject(pHandle, INFINITE) == WAIT_OBJECT_0)
    {
        exit(0);
    }
    return 0;
} 程序

相關文章
相關標籤/搜索