how to save system function output into a variable in c 2b 2b

Solutions on MaxInterview for how to save system function output into a variable in c 2b 2b by the best coders in the world

showing results for - "how to save system function output into a variable in c 2b 2b"
Raphaël
15 Aug 2019
1#include <windows.h>
2#include <atlstr.h>
3//
4// Execute a command and get the results. (Only standard output)
5//
6CStringA ExecCmd(
7    const wchar_t* cmd              // [in] command to execute
8)
9{
10    CStringA strResult;
11    HANDLE hPipeRead, hPipeWrite;
12
13    SECURITY_ATTRIBUTES saAttr = {sizeof(SECURITY_ATTRIBUTES)};
14    saAttr.bInheritHandle = TRUE; // Pipe handles are inherited by child process.
15    saAttr.lpSecurityDescriptor = NULL;
16
17    // Create a pipe to get results from child's stdout.
18    if (!CreatePipe(&hPipeRead, &hPipeWrite, &saAttr, 0))
19        return strResult;
20
21    STARTUPINFOW si = {sizeof(STARTUPINFOW)};
22    si.dwFlags     = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
23    si.hStdOutput  = hPipeWrite;
24    si.hStdError   = hPipeWrite;
25    si.wShowWindow = SW_HIDE; // Prevents cmd window from flashing.
26                              // Requires STARTF_USESHOWWINDOW in dwFlags.
27
28    PROCESS_INFORMATION pi = { 0 };
29
30    BOOL fSuccess = CreateProcessW(NULL, (LPWSTR)cmd, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi);
31    if (! fSuccess)
32    {
33        CloseHandle(hPipeWrite);
34        CloseHandle(hPipeRead);
35        return strResult;
36    }
37
38    bool bProcessEnded = false;
39    for (; !bProcessEnded ;)
40    {
41        // Give some timeslice (50 ms), so we won't waste 100% CPU.
42        bProcessEnded = WaitForSingleObject( pi.hProcess, 50) == WAIT_OBJECT_0;
43
44        // Even if process exited - we continue reading, if
45        // there is some data available over pipe.
46        for (;;)
47        {
48            char buf[1024];
49            DWORD dwRead = 0;
50            DWORD dwAvail = 0;
51
52            if (!::PeekNamedPipe(hPipeRead, NULL, 0, NULL, &dwAvail, NULL))
53                break;
54
55            if (!dwAvail) // No data available, return
56                break;
57
58            if (!::ReadFile(hPipeRead, buf, min(sizeof(buf) - 1, dwAvail), &dwRead, NULL) || !dwRead)
59                // Error, the child process might ended
60                break;
61
62            buf[dwRead] = 0;
63            strResult += buf;
64        }
65    } //for
66
67    CloseHandle(hPipeWrite);
68    CloseHandle(hPipeRead);
69    CloseHandle(pi.hProcess);
70    CloseHandle(pi.hThread);
71    return strResult;
72} //ExecCmd
73
similar questions