【发布时间】:2020-07-29 17:45:13
【问题描述】:
我的应用程序使用 createprocess(windows api) 并行(使用线程)运行特定数量的进程(不同的可执行文件)。用户可以随时刷新/关闭我的应用程序。到目前为止,我正在将进程句柄推入向量,并且每当收到关闭请求时,我都会迭代向量并终止(使用 GetExitCodeProcess 和 TerminateProcess API)并关闭(使用 CloseHandle API)进程句柄。此外,当它完成时,我正在关闭进程的句柄。当前模型的问题是,每当处理完成的句柄将被关闭并且当再次收到关闭请求时,我将尝试使用向量关闭它(句柄未更新)。为了解决这个问题,我必须在向量中/从向量中更新/删除句柄。为此,需要维护索引。
由于我知道进程的数量,我想创建一个静态向量并对其进行更新,而不是将本地对象推送到向量。有人可以提出一个最好的方法。 下面是示例代码。
//member object
std::vector<PROCESS_INFORMATION> mProcessHandles;
//this is a thread and will be called multiple times with different executable names in the application
void method(std::string executable)
{
STARTUPINFO startInfo{};
PROCESS_INFORMATION procInfo{};
bool ret = CreateProcess(NULL, executable, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &startInfo, &procInfo);
mProcessInfo.push_back(procInfo);
if(ret)
{
WaitForSingleObject(procInfo.hProcess, INFINITE);
CloseHandle(procInfo.hProcess);
procInfo.hProcess = NULL;
CloseHandle(procInfo.hThread);
procInfo.hThread = NULL;
}
return;
}
//this will be called when application close requested
void forceKill()
{
for (auto &processHandlesIt : mProcessHandles)
{
DWORD errorcode = 0;
GetExitCodeProcess(processHandlesIt.hProcess, &errorcode);
if (errorcode == STILL_ACTIVE)
{
TerminateProcess(processHandlesIt.hProcess, errorcode);
}
CloseHandle(processHandlesIt.hProcess);
processHandlesIt.hProcess = NULL;
CloseHandle(processHandlesIt.hThread);
processHandlesIt.hThread = NULL;
}
}
【问题讨论】:
-
你现在的做法很好,为什么要改变它或使用静态向量?如果您事先知道项目的数量,固定数组将是更好的选择。但是,一般方法或多或少是相同的。
-
您对
push_back的调用应该是同步的,因为std::vector不是线程安全的。或者,您可以使用静态数组并将索引传递给您的线程函数,这样每个线程都会使用自己的元素。