CCF
Loading...
Searching...
No Matches
system.h
Go to the documentation of this file.
1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the Apache 2.0 License.
3#pragma once
4
5#include "ccf/ds/logger.h"
6#include "ccf/ds/nonstd.h"
7
8#include <array>
9#include <cstdio>
10#include <cstdlib>
11#include <iostream>
12#include <string>
13
15{
16 std::optional<std::string> exec(const std::string& cmd)
17 {
18 std::array<char, 4096> buffer;
19 std::string result;
20
21 LOG_TRACE_FMT("Opening pipe to execute command: {}", cmd);
22 FILE* pipe = popen(cmd.c_str(), "r");
23 if (!pipe)
24 {
25 LOG_FAIL_FMT("Error opening pipe: {}", strerror(errno));
26 return std::nullopt;
27 }
28
29 while (fgets(buffer.data(), buffer.size(), pipe) != NULL)
30 {
31 result += buffer.data();
32 }
33
34 auto return_code = pclose(pipe);
35 if (return_code != 0)
36 {
37 LOG_TRACE_FMT("Command returned error: {}", return_code);
38 }
39
40 result = ccf::nonstd::trim(result);
41
42 LOG_TRACE_FMT("Result is: {}", result);
43
44 return result;
45 }
46}
#define LOG_TRACE_FMT
Definition logger.h:356
#define LOG_FAIL_FMT
Definition logger.h:363
Definition system.h:15
std::optional< std::string > exec(const std::string &cmd)
Definition system.h:16