使用Win32执行命令

时间:2015-07-22 12:46:39

标签: 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);

2 个答案:

答案 0 :(得分:3)

使用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);

答案 1 :(得分:1)

问题解决了! 完整代码:

STARTUPINFO si = { sizeof(STARTUPINFO) };
PROCESS_INFORMATION pi;

if (!CreateProcess(L"C:\\Windows\\System32\\cmd.exe",
    L" /C avrdude.exe -c breakout -P ft0 -p m2560 -U flash:w:\"file.cpp.hex\":a",
    NULL, NULL, 0, 0, NULL, NULL, &si, &pi))    
{
    printf("CreateProcess failed (%d).\n", GetLastError());
    return -1;
}