在 C++ Windows 应用程序中,我启动了几个长时间运行的子进程(目前我使用 CreateProcess(...) 来执行此操作。
我希望子进程在我的主进程崩溃或关闭时自动关闭。
由于要求这需要在“父”崩溃时起作用,我相信这需要使用操作系统的某些 API/功能来完成。以便清理所有“子”进程。
我该怎么做?
最佳答案
Windows API 支持称为“作业对象”的对象。以下代码将创建一个“作业”,该作业被配置为在主应用程序结束时(清理其句柄时)关闭所有进程。这段代码应该只运行一次。:
HANDLE ghJob = CreateJobObject( NULL, NULL); // GLOBAL
if( ghJob == NULL)
{
::MessageBox( 0, "Could not create job object", "TEST", MB_OK);
}
else
{
JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };
// Configure all child processes associated with the job to terminate when the
jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if( 0 == SetInformationJobObject( ghJob, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli)))
{
::MessageBox( 0, "Could not SetInformationJobObject", "TEST", MB_OK);
}
}
然后在创建每个子进程时,执行以下代码来启动每个子进程并将其添加到作业对象中:
STARTUPINFO info={sizeof(info)};
PROCESS_INFORMATION processInfo;
// Launch child process - example is notepad.exe
if (::CreateProcess( NULL, "notepad.exe", NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))
{
::MessageBox( 0, "CreateProcess succeeded.", "TEST", MB_OK);
if(ghJob)
{
if(0 == AssignProcessToJobObject( ghJob, processInfo.hProcess))
{
::MessageBox( 0, "Could not AssignProcessToObject", "TEST", MB_OK);
}
}
// Can we free handles now? Not sure about this.
//CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
}
VISTA 注意:参见 AssignProcessToJobObject always return "access denied" on Vista如果您在 vista 上使用 AssignProcessToObject() 遇到拒绝访问的问题。
关于windows - 如何在 Windows 中自动销毁子进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53208/