Shamrock 2025.10.0
Astrophysical Code
Loading...
Searching...
No Matches
popen.cpp
Go to the documentation of this file.
1// -------------------------------------------------------//
2//
3// SHAMROCK code for hydrodynamics
4// Copyright (c) 2021-2026 Timothée David--Cléris <tim.shamrock@proton.me>
5// SPDX-License-Identifier: CeCILL Free Software License Agreement v2.1
6// Shamrock is licensed under the CeCILL 2.1 License, see LICENSE for more information
7//
8// -------------------------------------------------------//
9
18#include "shambase/popen.hpp"
19#include <stdexcept>
20
21namespace shambase {
22
23 std::string popen_fetch_output(const char *command) {
24
25 char buffer[128];
26 std::string result;
27 FILE *pipe = popen(command, "r");
28 if (!pipe)
29 throw_with_loc<std::runtime_error>("popen() failed!");
30
31 try {
32 while (fgets(buffer, sizeof buffer, pipe) != nullptr) {
33 result += buffer;
34 }
35 } catch (...) {
36
37 int exit_status = pclose(pipe);
38 if (exit_status != 0) {
40 "Command failed with exit status " + std::to_string(exit_status));
41 }
42
43 throw;
44 }
45
46 int exit_status = pclose(pipe);
47 if (exit_status != 0) {
49 "Command failed with exit status " + std::to_string(exit_status));
50 }
51
52 return result;
53 }
54
55} // namespace shambase
This header file contains utility functions related to exception handling in the code.
namespace for basic c++ utilities
void throw_with_loc(std::string message, SourceLocation loc=SourceLocation{})
Throw an exception and append the source location to it.
std::string popen_fetch_output(const char *command)
Run a command and return the output.
Definition popen.cpp:23