C/C++ · 2023年9月28日 0

Windows C++ 启动子进程并绑定子进程,主进程结束关闭后自动结束关闭子进程

	// 启动子进程
	STARTUPINFO StartupInfo;
	PROCESS_INFORMATION ProcessInformation;
	ZeroMemory(&StartupInfo, sizeof(StartupInfo));
	ZeroMemory(&ProcessInformation, sizeof(ProcessInformation));
	StartupInfo.cb = sizeof(StartupInfo);
	StartupInfo.wShowWindow = SW_SHOW;
	CreateProcess(L"child.exe", nullptr, nullptr, nullptr, 0, 0, nullptr, nullptr, &StartupInfo, &ProcessInformation);

 	// 把子进程加入到作业中
	HANDLE HandleJob = CreateJobObject(nullptr, nullptr);
	if(AssignProcessToJobObject(HandleJob, ProcessInformation.hProcess))
	{
		JOBOBJECT_EXTENDED_LIMIT_INFORMATION LimitInfo;
		ZeroMemory(&LimitInfo, sizeof(LimitInfo));
		LimitInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; 
		SetInformationJobObject(HandleJob, JobObjectExtendedLimitInformation, &LimitInfo, sizeof(LimitInfo));	
	}

最后调用 CloseHandle(HandleJob); 就可以关闭子进程。

但是我们需要的是主进程退出以后,子进程才自动关闭, 所以不需要调用 CloseHandle(HandleJob);. 在主程序关闭以后,HandleJob 会被自动回收,子进程也跟着一起关闭了。

80后程序员