Waitforsingleobject检测系统命令退出

时间:2014-05-12 07:01:26

标签: c++ visual-studio

您好我想为allegro执行系统命令并等到它完成,因为我需要访问此命令生成的文件。我的代码不起作用。有人可以帮忙吗?命令没有运行?如果我做系统(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);

1 个答案:

答案 0 :(得分:0)

我认为你不需要&#34;开始&#34;在命令开头,即使您使用标志CREATE_NEW_CONSOLE。 &#34;开始&#34;适用于system(因为system适用于批处理命令),但如果要创建新进程,则只应指定映像文件的路径。顺便说一句,知道发生了什么的唯一方法是检查CreateProcess(最终GetLastError())的回报。

此外,这不是使用WaitForSingleObject的最佳方式。您应该抓住WAIT_FAILED并使用GetLastError(),否则您在SO上的下一篇文章将是:&#34;为什么我的程序没有等待?&#34; : - )

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

相关问题