【问题标题】:How to make the program waits till the command is executed如何让程序等到命令执行
【发布时间】:2013-07-20 09:04:28
【问题描述】:

我正在尝试通过程序执行系统命令,然后等待进程终止以继续执行代码指令。我一直在使用sleep(),但它没有成功,因为它是相对的,我的意思是执行时间因机器而异......所以有什么解决方案吗?

考虑下面的代码(语言==c++):

ShellExecute(0, "open", "cmd.exe","/C rasdial adsl user pwd", 0, SW_HIDE); //can also use system().
Sleep(sec);
if(CheckConnection()) {cout <<"U r connected"; }

等到系统命令执行后检查连接(我想你现在明白了)。

【问题讨论】:

  • MSVC++ 是否支持system 函数?如果是这样,你可以这样做system("cmd.exe /C rasdial adsl user pwd")
  • 是的,它支持...但问题是我不想获得执行的输出

标签: c++ shell command


【解决方案1】:

使用 ShellExecuteEx 代替 ShellExecute,然后使用收到的 hProcess 调用 WaitForSingleObject:

SHELLEXECUTEINFO info = { sizeof(SHELLEXECUTEINFO) };
// fill in values in SHELLEXECUTEINFO as necessary
if (ShellExecuteEx(&info))
{
    WaitForSingleObject (info.hProcess, INFINITY);
    // The new process has now completed
}
else
{
    // Launch failed
}

【讨论】:

    【解决方案2】:

    使用CreateProcee你有更多的选择看这个例子http://msdn.microsoft.com/en-us/library/windows/desktop/ms682512(v=vs.85).aspxWaitForSingleObject等待程序完成

    【讨论】:

    • 这是一个很好的解决方案..thnx
    • 我不知道为什么我不断收到错误 CreateProcess failed (2)。 (甚至使用微软给出的代码)
    • @user2355950 您能否将GetLastError 的结果扩展为FormatMessage(因为它在页面下方的示例msdn.microsoft.com/en-us/library/ms679351%28v=VS.85%29.aspx 中使用)并告诉我您看到的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-24
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    相关资源
    最近更新 更多