我想像这样执行 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/