windows 子進程獲取父進程的方法。

子進程獲取父進程可以通過微軟未公開的一個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 instance
	HINSTANCE hPrevInstance,  // handle to previous instance
	LPSTR lpCmdLine,          // command line
	int nCmdShow              // show state
	)
{
	DWORD pid;
	char char_main_id [16];
	sprintf_s(char_main_id , "%s" , &lpCmdLine[0]);
	pid = atoi(char_main_id);

	...
}


有了 pid,就什麼都好說了。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章