Loading...
Searching...
No Matches
ExternalCommand.h
Go to the documentation of this file.
1/*
2** This file is part of eOn.
3**
4** SPDX-License-Identifier: BSD-3-Clause
5**
6** Copyright (c) 2010--present, eOn Development Team
7** All rights reserved.
8**
9** Repo:
10** https://github.com/TheochemUI/eOn
11*/
12#pragma once
13
14#include <cstdlib>
15#include <stdexcept>
16#include <string>
17
18#ifndef _WIN32
19#include <sys/wait.h>
20#endif
21
22namespace eonc::pot {
23
29[[nodiscard]] inline std::string commandFailure(int status) {
30 if (status == -1) {
31 return "could not be started";
32 }
33#ifndef _WIN32
34 if (WIFSIGNALED(status)) {
35 return "died on signal " + std::to_string(WTERMSIG(status));
36 }
37 if (!WIFEXITED(status)) {
38 return "terminated abnormally";
39 }
40 if (WEXITSTATUS(status) != 0) {
41 return "exited with status " + std::to_string(WEXITSTATUS(status));
42 }
43#else
44 if (status != 0) {
45 return "exited with status " + std::to_string(status);
46 }
47#endif
48 return {};
49}
50
56inline void runOrThrow(const std::string &command) {
57 const std::string reason = commandFailure(std::system(command.c_str()));
58 if (!reason.empty()) {
59 throw std::runtime_error("Command \"" + command + "\" " + reason);
60 }
61}
62
63} // namespace eonc::pot
std::string commandFailure(int status)
Describe how a command run through system() ended.
void runOrThrow(const std::string &command)
Run a shell command, throwing when it does not succeed.