对于我的应用程序,我试图关闭一个 Python 进程并使用“subprocess.Popen”打开它的衍生进程。我尝试了 TerminateProcess,它太邪恶了。 :) 我终于确定我可以使用控制台命令taskkill。我在 C++ 程序中做到了这一点:
// standard kill process call
void stopProcess(DWORD pid)
{
STARTUPINFO startupInfo;
LPPROCESS_INFORMATION processInfo = new PROCESS_INFORMATION;
// clear the memory to prevent garbage
ZeroMemory(&startupInfo, sizeof(startupInfo));
// set size of structure (not using Ex version)
startupInfo.cb = sizeof(STARTUPINFO);
// tell the application that we are setting the window display
// information within this structure
startupInfo.dwFlags = STARTF_USESHOWWINDOW;
// hide process
startupInfo.wShowWindow = SW_HIDE;
//TerminateProcess(itr->second->hProcess, 0); // not friendly to process, and does not kill child processes
std::stringstream comStream;
comStream << "taskkill /pid ";
comStream << pid;
//comStream << " /t /f"; // to be more like TerminateProcess
_MESSAGE("%s", comStream.str().c_str());
//system(comStream.str().c_str()); // works, but pops up a window momentarilly when called
//LPSTR s = const_cast<char *>(comStream.str().c_str());
LPSTR cString = strdup( comStream.str().c_str() );
if(!CreateProcess(NULL,cString,NULL,NULL,false,NORMAL_PRIORITY_CLASS,NULL,NULL,&startupInfo,processInfo)){
_MESSAGE("Could not launch '%s'",cString);
SAFE_DELETE(processInfo);
}else{
// clean up
CloseHandle(processInfo);
SAFE_DELETE(processInfo);
}
// clean up
free(cString);
}
你会看到我的其他实验被注释掉了。我最终选择了这种方法,因为它隐藏了任何可能出现的弹出窗口。我还发现这允许 Python 应用程序正确调用 atexit。但是,即使我没有明确结束子进程,它们还是会使用 taskkill 方法关闭。我猜这是由于 Python 代码的设计方式造成的。
所以,你可以试试上面的方法,等待进程关闭,如果失败了,如果它不配合,你可以使用 TerminateProcess 切换到大炮。如果需要,Taskkill 也有无情杀戮的模式。