重定向

bool RandAndSeq::RunCmdAndOutPutRedirect(const std::string &outPutFile,
                                         const std::string &cmd,
                                         bool wait = false)
{
    LOG_INFO << "outPutFile:" << outPutFile << " cmd:"
        << cmd << " wait:" << wait;
    STARTUPINFOA si;
    PROCESS_INFORMATION pi;

    SECURITY_ATTRIBUTES sa;
    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE;
    HANDLE handle = CreateFileA(outPutFile.c_str(),
                                FILE_APPEND_DATA,
                                FILE_SHARE_WRITE | FILE_SHARE_READ,
                                &sa,
                                CREATE_ALWAYS,
                                FILE_ATTRIBUTE_NORMAL,
                                NULL);
    if (!handle)
    {
        LOG_WARN << "CreateFile failed:" << GetLastError();
        return false;
    }

    memset(&si, 0, sizeof(STARTUPINFO));
    memset(&pi, 0, sizeof(PROCESS_INFORMATION));
    si.cb = sizeof(STARTUPINFO);
    si.dwFlags |= STARTF_USESTDHANDLES;
    si.wShowWindow = SW_HIDE;
    si.wShowWindow = SW_SHOWNORMAL;
    si.hStdInput = NULL;
    si.hStdError = NULL;
    si.hStdOutput = handle;

    if (!CreateProcessA(NULL,
        (LPSTR)cmd.c_str(),
        NULL,
        NULL,
        TRUE,
        CREATE_NO_WINDOW,
        NULL,
        NULL,
        &si,
        &pi))
    {
        LOG_WARN << "CreateProcess failed:" << GetLastError();
        CloseHandle(handle);
        return false;
    }

    if (wait)
    {
        WaitForSingleObject(pi.hProcess, INFINITE);
    }
    LOG_WARN << "WaitForSingleObject finish return:" << GetLastError();
    CloseHandle(handle);
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
    return true;
}


void RandAndSeq::RedirectCmd()
{
    PVOID oldValue = NULL;
    if (Wow64DisableWow64FsRedirection(&oldValue))
    {
        std::string filePath = temp_file_path::kRandAndseqPath;
        std::string cmd = "winsat disk";
        RunCmdAndOutPutRedirect(filePath, cmd, true);
    }
    else
    {
        LOG_WARN << "重定向失败.ErrorCode: " << GetLastError();
    }
    if (Wow64RevertWow64FsRedirection(oldValue) == FALSE)
    {
        LOG_WARN << "恢复调用线程的文件系统重定向失败. ErrorCode:" << GetLastError();
        return;
    }
}

 

比如X64系统无法使用X32目录下的cmd等等。如:winsat必须是X32目录下cmd才存在。

也可以重定向X64或X32的注册表

posted @ 2019-11-24 16:25  gd_沐辰  阅读(224)  评论(0编辑  收藏  举报