c++ - 使用 Win32 执行命令

标签 c++ winapi cmd createprocess

我想像这样执行 shell 命令来更新我的处理器 ATMega 2560 的固件:

avrdude.exe -c breakout -P ft0 -p m2560 -U flash:w:\"file.cpp.hex\":a

我可以通过 ShellExecute() 函数来完成:

ShellExecute(0, L"open", L"cmd.exe", L"/C avrdude.exe -c breakout -P ft0 -p     m2560 -U flash:w:\"file.cpp.hex\":a > log.txt", 0, SW_HIDE);

但是我想重定向输出缓冲区,所以我想我应该使用 CreateProcess() 函数。我试过了,但没用。

CreateProcess(NULL, L"cmd /C avrdude.exe -c breakout -P ft0 -p m2560 -U flash:w:\"file.cpp.hex\":a", NULL, NULL, 0, 0, NULL, NULL, NULL, NULL);

最佳答案

使用 CreateProcess() 而不是 ShellExecute(),并提供您自己的管道以便您可以读取进程的输出。 MSDN 有一篇关于该主题的文章:

Creating a Child Process with Redirected Input and Output

例如:

LPWSTR cmdLine[] = L"avrdude.exe -c breakout -P ft0 -p m2560 -U flash:w:\"file.cpp.hex\":a";

SECURITY_ATTRIBUTES sa = {0};
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;

HANDLE hStdOutRd, hStdOutWr;
HANDLE hStdErrRd, hStdErrWr;

if (!CreatePipe(&hStdOutRd, &hStdOutWr, &sa, 0))
{
    // error handling...
}

if (!CreatePipe(&hStdErrRd, &hStdErrWr, &sa, 0))
{
    // error handling...
}

SetHandleInformation(hStdOutRd, HANDLE_FLAG_INHERIT, 0);
SetHandleInformation(hStdErrRd, HANDLE_FLAG_INHERIT, 0);

STARTUPINFO si = {0};
si.cbSize = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
si.hStdOutput = hStdOutWr;
si.hStdError = hStdErrWr;

PROCESS_INFORMATION pi = {0};

if (!CreateProcessW(NULL, cmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
{
    // error handling...
}
else
{
    // read from hStdOutRd and hStdErrRd as needed until the process is terminated...

    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
}

CloseHandle(hStdOutRd);
CloseHandle(hStdOutWr);
CloseHandle(hStdErrRd);
CloseHandle(hStdErrWr);

关于c++ - 使用 Win32 执行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31563579/

相关文章:

c++ - 什么会导致调试断言错误。具体来说,在我的代码中

c++ - 如何在 Qt 中发出跨线程信号?

c++ - C++ 上的 SendInput 不考虑 Ctrl 和 Shift

windows - 暂时打开回声

batch-file - 带管道的 Windows 2003 批处理脚本

android - 通过cmd创建android项目

c++ - 如何修改我的Qt PaintEvent代码以相对于鼠标指针缩放显示的Pixmap

c++ - 嵌入式平台上的 OpenCV

c++ - 打印作业时,最后的作业状态是 JOB_STATUS_PAUSED,而不是 JOB_STATUS_PRINTED

c++ - 是否有不搜索短文件名的 Windows FindFirstFile/FindNextFile API 的替代方法?