CreateProcess将运行结果写入文件

PROCESS_INFORMATION pi;
    STARTUPINFO si = { sizeof(STARTUPINFO) };
    SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES),NULL,TRUE };
    HANDLE cmdOutput = CreateFile("./output.txt",
        GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
        &sa, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (cmdOutput == INVALID_HANDLE_VALUE)
    {
        ExitProcess(0);
    }
    SetFilePointer(cmdOutput, 0, 0, FILE_END); //CreateFile文件追加写入
    HANDLE cmdInput = CreateFile("./input.txt",
        GENERIC_READ,
        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
        &sa, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (cmdInput == INVALID_HANDLE_VALUE)
    {
        ExitProcess(0);
    }

    si.hStdInput = cmdInput;
    si.hStdOutput = cmdOutput;
    si.dwFlags = STARTF_USESTDHANDLES;
    std::string cmdstr = "ping 8.8.8.8";
    LPSTR lpszCmdLine = (LPSTR)cmdstr.c_str();
    if (CreateProcess(NULL, lpszCmdLine, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi))
    {
        WaitForSingleObject(pi.hProcess, INFINITE);
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
    }

    CloseHandle(cmdOutput);
    CloseHandle(cmdInput);

你可能感兴趣的:(C++)