Waitforsingleobject用于检测系统命令退出

Waitforsingleobject to detect a system command exit

本文关键字:退出 系统命令 检测 用于 Waitforsingleobject      更新时间:2023-10-16

嗨,我想为allegro执行一个系统命令,并等待它完成,因为我需要访问该命令生成的文件。我的代码不工作。有人能帮帮我吗?命令没有运行?如果我执行system(command.c_str())但不等待,它就会工作。

string command = "start allegro -expert -nographic -s " + fileName1 + " " + boardFile1;
 bool ret;
bool retwait;
STARTUPINFO startupinfo;
GetStartupInfo (&startupinfo);
PROCESS_INFORMATION pro2info;
LPTSTR cmdL = (LPTSTR)command.c_str();
ret = CreateProcess(NULL, cmdL, NULL, NULL, false, CREATE_NEW_CONSOLE, NULL,NULL, &startupinfo, &pro2info);
cout<<"hProcess: "<<pro2info.hProcess<<endl;
cout<<"dwProcessId: "<<pro2info.dwProcessId <<endl;
//Want to wait till the command executes
while (retwait= WaitForSingleObject (pro2info.hProcess, INFINITE)!=WAIT_OBJECT_0)
    cout<<"waitprocess:true"<<endl; //The process is finished;
CloseHandle (pro2info.hProcess);

我认为您不需要在命令开始时使用"start",即使您正在使用标志CREATE_NEW_CONSOLE。"start"适用于system(因为system适用于批处理命令),但是如果您正在创建一个新进程,您应该只指定映像文件的路径。顺便说一下,知道发生了什么事的唯一方法是检查CreateProcess(最终是GetLastError())的返回。

同样,这也不是使用WaitForSingleObject的最佳方式。你应该抓住WAIT_FAILED并使用GetLastError(),否则你的下一篇关于SO的文章将是:"为什么我的程序不等待?": -)

http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425%28v=vs.85%29.aspx