Fray Engine
Loading...
Searching...
No Matches
process_manager.hpp
Go to the documentation of this file.
1/* process_manager.hpp */
2
3#ifndef _FRAY_PROCESS_MANAGER_HPP_
4#define _FRAY_PROCESS_MANAGER_HPP_
5
6#include <cstdlib>
7#include <filesystem>
8#include <string>
9#include <utility>
10#include <vector>
11
12#ifdef _WIN32
13#include <windows.h>
14#else
15#include <sys/types.h>
16#include <unistd.h>
17#endif
18
19#include "errors.hpp"
20#include "log_manager.hpp"
21#include "types.hpp"
22
23namespace fray
24{
25 namespace process
26 {
38 inline F_err spawn(
39 const std::vector<std::string> &command,
40 const std::filesystem::path &workingDirectory,
41 const std::vector<std::pair<std::string, std::string>> &environment = {})
42 {
43 if (command.empty())
44 {
45 log::engineError("Cannot spawn a process: empty command.");
46 return errors::FAILED_SPAWN_PROCESS;
47 }
48
49 // The environment is changed before the spawn while the engine is still single-threaded.
50 for (const auto &variable : environment)
51#ifdef _WIN32
52 _putenv_s(variable.first.c_str(), variable.second.c_str());
53
54 std::string commandLine = "cmd /c";
55 for (const auto &argument : command)
56 commandLine += " " + argument;
57 STARTUPINFOA startup{};
58 startup.cb = sizeof(startup);
59 PROCESS_INFORMATION info{};
60 const std::string directory = workingDirectory.string();
61 if (!CreateProcessA(nullptr, commandLine.data(), nullptr, nullptr, TRUE, 0, nullptr,
62 directory.c_str(), &startup, &info))
63 {
64 log::engineError("Failed to spawn %s.", command.front().c_str());
65 return errors::FAILED_SPAWN_PROCESS;
66 }
67 CloseHandle(info.hThread);
68 CloseHandle(info.hProcess);
69#else
70 setenv(variable.first.c_str(), variable.second.c_str(), 1);
71
72 const pid_t child = fork();
73 if (child < 0)
74 {
75 log::engineError("Failed to spawn %s.", command.front().c_str());
76 return errors::FAILED_SPAWN_PROCESS;
77 }
78 if (child == 0)
79 {
80 if (chdir(workingDirectory.c_str()) != 0)
81 _exit(126);
82 std::vector<char *> arguments;
83 for (const auto &argument : command)
84 arguments.push_back(const_cast<char *>(argument.c_str()));
85 arguments.push_back(nullptr);
86 execvp(arguments[0], arguments.data());
87 _exit(127);
88 }
89#endif
90 log::engineInfo("Spawned %s.", command.front().c_str());
91 return errors::NONE;
92 }
93 } // namespace process
94} // namespace fray
95
96#endif
F_long F_err
Error return type used across the Engine; the value is a fray::errors::code (0 / NONE means success).
Definition errors.hpp:13
F_void engineInfo(const F_char *fmt,...)
Log info for Engine.
F_void engineError(const F_char *fmt,...)
Log error for Engine.
F_err spawn(const std::vector< std::string > &command, const std::filesystem::path &workingDirectory, const std::vector< std::pair< std::string, std::string > > &environment={})
Starts a child process without waiting for it (fire and forget). The child inherits this process's st...