aboutsummaryrefslogtreecommitdiff
path: root/src/Exec.cpp
blob: 37ffef58a48cb3a2d20dccd7781d5d7145603b76 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include "../include/Exec.hpp"

using namespace std;

namespace sibs
{
    Result<ExecResult> exec(const char *cmd, bool print)
    {
        char buffer[128];
        std::string result;
        FILE *pipe = popen(cmd, "r");
        if(!pipe)
            return Result<ExecResult>::Err("popen() failed");

        while(!feof(pipe))
        {
            if(fgets(buffer, 128, pipe))
            {
                result += buffer;
                if(print)
                    printf("%s", buffer);
            }
        }

        int processCloseResult = pclose(pipe);
        if(WIFEXITED(processCloseResult))
        {
            int returned = WEXITSTATUS(processCloseResult);
            ExecResult execResult;
            execResult.execStdout = result;
            execResult.exitCode = returned;
            return Result<ExecResult>::Ok(execResult);
        }
        else if(WIFSIGNALED(processCloseResult))
        {
            int signum = WSTOPSIG(processCloseResult);
            string errMsg = "Exited due to receiving signal ";
            errMsg += to_string(signum);
            return Result<ExecResult>::Err(errMsg);
        }
        else if(WIFSTOPPED(processCloseResult))
        {
            int signum = WSTOPSIG(processCloseResult);
            string errMsg = "Stopped due to receiving signal ";
            errMsg += to_string(signum);
            return Result<ExecResult>::Err(errMsg);
        }
        else
        {
            string errMsg = "exec unexpected error on pclose: ";
            errMsg += to_string(processCloseResult);
            return Result<ExecResult>::Err(errMsg);
        }
    }
}