Bitcoin Core
32.1.0
P2P Digital Currency
Toggle main menu visibility
Loading...
Searching...
No Matches
src
common
run_command.cpp
Go to the documentation of this file.
1
// Copyright (c) 2022-present The Bitcoin Core developers
2
// Distributed under the MIT software license, see the accompanying
3
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5
#include <
common/run_command.h
>
6
7
#include <
tinyformat.h
>
8
#include <
univalue.h
>
9
#include <
util/string.h
>
10
#include <
util/subprocess.h
>
11
12
#include <sstream>
13
#include <stdexcept>
14
#include <utility>
15
16
UniValue
RunCommandParseJSON
(
const
std::vector<std::string>& cmd_args,
const
std::string& str_std_in)
17
{
18
namespace
sp =
subprocess
;
19
20
UniValue
result_json;
21
std::istringstream stdout_stream;
22
std::istringstream stderr_stream;
23
24
if
(cmd_args.empty())
return
UniValue::VNULL
;
25
26
auto
c = sp::Popen(cmd_args, sp::input{sp::PIPE}, sp::output{sp::PIPE}, sp::error{sp::PIPE});
27
if
(!str_std_in.empty()) {
28
c.send(str_std_in);
29
}
30
auto
[out_res, err_res] = c.communicate();
31
stdout_stream.str(std::string{out_res.buf.begin(), out_res.buf.end()});
32
stderr_stream.str(std::string{err_res.buf.begin(), err_res.buf.end()});
33
34
std::string result;
35
std::string error;
36
std::getline(stdout_stream, result);
37
std::getline(stderr_stream, error);
38
39
const
int
n_error = c.retcode();
40
if
(n_error)
throw
std::runtime_error(
strprintf
(
"RunCommandParseJSON error: process(%s) returned %d: %s\n"
,
util::Join
(cmd_args,
" "
), n_error, error));
41
if
(!result_json.
read
(result))
throw
std::runtime_error(
"Unable to parse JSON: "
+ result);
42
43
return
result_json;
44
}
UniValue
Definition
univalue.h:22
UniValue::VNULL
@ VNULL
Definition
univalue.h:24
UniValue::read
bool read(std::string_view json)
Parse JSON; set value to null on failure.
Definition
univalue_read.cpp:264
subprocess
Definition
subprocess.h:109
util::Join
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition
string.h:209
RunCommandParseJSON
UniValue RunCommandParseJSON(const std::vector< std::string > &cmd_args, const std::string &str_std_in)
Execute a command which returns JSON, and parse the result.
Definition
run_command.cpp:16
run_command.h
string.h
subprocess.h
tinyformat.h
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition
tinyformat.h:1172
univalue.h
Generated on
for Bitcoin Core by
1.18.0