windows 子进程获取父进程的方法。

来源:互联网 发布:南大 知乎 编辑:程序博客网 时间:2024/05/18 03:11

子进程获取父进程可以通过微软未公开的一个api实现

NTSTATUS WINAPI NtQueryInformationProcess(
__in HANDLE ProcessHandle,
__in PROCESSINFOCLASS ProcessInformationClass,
__out PVOID ProcessInformation,
__in ULONG ProcessInformationLength,
__out_opt PULONG ReturnLength
);

但是既然未公开,肯定有不公开的理由,这里打算不用这种方式

我的做法是在 父进程创建子进程的时候,传入一个参数,这个参数就是自己的进程id。

父进程:

void startModule1(){std::stringstream ss;ss << "module1 "; //注意这里要有空格,module1就是子进程的 exe 文件名ss << GetCurrentProcessId();std::string moduleName = ss.str();STARTUPINFO si;PROCESS_INFORMATION pi;ZeroMemory( &si, sizeof(si) );si.cb = sizeof(si);ZeroMemory( &pi, sizeof(pi) );// Start the child process. if( !CreateProcess( NULL, LPSTR(moduleName.c_str()) ,NULL, NULL, TRUE, 0,  NULL, NULL, &si, &pi)) {return;}hd_dwld = pi.dwProcessId;// Wait until child process exits.WaitForSingleObject( pi.hProcess, INFINITE );// Close process and thread handles. CloseHandle( pi.hProcess );CloseHandle( pi.hThread );handleStop();}


子进程:

int WINAPI WinMain(HINSTANCE hInstance,      // handle to current instanceHINSTANCE hPrevInstance,  // handle to previous instanceLPSTR lpCmdLine,          // command lineint nCmdShow              // show state){DWORD pid;char char_main_id [16];sprintf_s(char_main_id , "%s" , &lpCmdLine[0]);pid = atoi(char_main_id);...}


有了 pid,就什么都好说了。。

原创粉丝点击