现在的位置: 首页 > 自动控制 > 工业·编程 > 正文

使用管道重定向方法获取windows下命令行执行程序结果

2014-03-18 06:24 工业·编程 ⁄ 共 1083字 ⁄ 字号 暂无评论

void CRedirectPipeDlg::OnBnClickedRunCmd()
{
    // TODO: Add your control notification handler code
    UpdateData();
    m_strOutput = "";
    SECURITY_ATTRIBUTES sa;
    HANDLE hRead,hWrite;
    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE;
    if (!CreatePipe(&hRead,&hWrite,&sa,0))
    {
        MessageBox(_T("Error On CreatePipe()"));
        return;
    }
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    si.cb = sizeof(STARTUPINFO);
    GetStartupInfo(&si);
    si.hStdError = hWrite;
    si.hStdOutput = hWrite;
    si.wShowWindow = SW_HIDE;
    si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
    CString strCmd(_T("cmd /C /"")+m_strCmd+_T("/""));
    if (!CreateProcess(NULL, (LPSTR)strCmd.GetString(), NULL, NULL, TRUE, NULL, NULL, NULL, &si,&pi))
    {
            MessageBox(_T("Error on CreateProcess()"));
            return;
    }
    CloseHandle(hWrite);
    char buffer[4096] = {0};
    DWORD bytesRead;
    while (true)
    {
        if (ReadFile(hRead,buffer,4095,&bytesRead,NULL) == NULL)
            break;
        m_strOutput += buffer;
        memset(buffer, 0, 4096);
        UpdateData(false);
        Sleep(200);
    }
}

给我留言

留言无头像?