1#include "service.hpp"
2
3#include "global.hpp"
4
5#include <unistd.h>
6
7bool Service::do_start()
8{
9 this->pid = fork();
10 if (this->pid == 0)
11 {
12 const char **argv = (const char **) malloc(size: sizeof(char *));
13 int argc = 1;
14 argv[0] = this->exec[0].c_str();
15
16 for (size_t i = 1; i < this->exec.size(); i++)
17 {
18 argc++;
19 argv = (const char **) realloc(pointer: argv, size: argc * sizeof(char *));
20 argv[argc - 1] = this->exec[i].c_str();
21 }
22
23 argv = (const char **) realloc(pointer: argv, size: (argc + 1) * sizeof(char *));
24 argv[argc] = NULL;
25
26 execv(this->exec[0].c_str(), (char **) argv);
27 return false;
28 }
29 else if (this->pid < 0)
30 {
31 std::cerr << "failed to start service " << id << std::endl;
32 return false;
33 }
34
35 service_pid[id] = this->pid;
36 return true;
37}
38
39bool Service::do_stop()
40{
41 std::cout << "stopping service " << id << std::endl;
42 return true;
43}
44
45bool Service::do_load(const toml::table &data)
46{
47 const auto exec = data["exec"];
48 if (!exec)
49 {
50 std::cerr << "service " << id << " missing exec" << std::endl;
51 return false;
52 }
53
54 if (exec.is_string())
55 {
56 this->exec.push_back(x: *exec.value_exact<std::string>());
57 }
58 else if (exec.is_array())
59 {
60 exec.as_array()->visit(visitor: array_append_visitor(this->exec));
61 }
62 else
63 {
64 std::cerr << "service " << id << " bad exec" << std::endl;
65 return false;
66 }
67
68 return true;
69}
70
71void Service::do_print(std::ostream &os) const
72{
73 os << " exec: ";
74 for (const auto &e : this->exec)
75 os << e << " ";
76 os << std::endl;
77}
78