SMACC2
Loading...
Searching...
No Matches
smacc_ros_launch_client_2.cpp
Go to the documentation of this file.
1// Copyright 2025 Robosoft Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15/*****************************************************************************************************************
16 *
17 * Authors: Pablo Inigo Blasco, Brett Aldrich
18 *
19 ******************************************************************************************************************/
20#include <errno.h>
21#include <poll.h>
22#include <signal.h>
23#include <stdio.h>
24#include <sys/types.h>
25#include <sys/wait.h>
26#include <unistd.h>
27#include <cstdio>
28#include <cstdlib>
29#include <cstring>
30#include <future>
31#include <iostream>
33#include <system_error>
34#include <thread>
35
36namespace smacc2
37{
38namespace client_bases
39{
40using namespace std::chrono_literals;
41ClRosLaunch2::ClRosLaunch2() : cancellationToken_(false) {}
42
43ClRosLaunch2::ClRosLaunch2(std::string packageName, std::string launchFilename)
44: packageName_(packageName), launchFileName_(launchFilename), cancellationToken_(false)
45{
46}
47
49
51{
52 cancellationToken_.store(false);
53 // Start the launch execution thread
54 this->result_ =
56}
57
59{
60 // Set the cancellation flag
61 cancellationToken_.store(true);
62}
63
64std::future<std::string> ClRosLaunch2::executeRosLaunch(
65 const std::string & packageName, const std::string & launchFileName,
66 std::function<bool()> cancelCondition, ClRosLaunch2 * client)
67{
68 return std::async(
69 std::launch::async,
70 [packageName, launchFileName, cancelCondition, client]()
71 {
72 RCLCPP_WARN_STREAM(rclcpp::get_logger("smacc2"), "[ClRosLaunch2] Starting ros launch thread");
73
74 std::stringstream cmd;
75 cmd << "ros2 launch " << packageName << " " << launchFileName;
76 std::array<char, 128> buffer{};
77 std::string result;
78
79 auto child = runProcess(cmd.str().c_str());
80
81 if (!child.pipe)
82 {
83 // Logged, not thrown: nothing reads this future in LAUNCH_CLIENT_BEHAVIOR_LIFETIME mode.
84 RCLCPP_ERROR_STREAM(
85 rclcpp::get_logger("smacc2"), "[ClRosLaunch2] could not start: " << cmd.str());
86 return result;
87 }
88 if (client != nullptr)
89 {
90 client->launchPid_ = child.pid;
91 }
92
93 int fd = fileno(child.pipe.get());
94 bool cancelled = false;
95
96 // poll() with a 100 ms timeout is also the cancel-check cadence. read() returning 0 is the
97 // launch tree's end of file, which the former non-blocking fread() loop took for "no data yet".
98 while (!cancelled)
99 {
100 cancelled = cancelCondition();
101 pollfd pfd{fd, POLLIN, 0};
102 int ready = poll(&pfd, 1, 100);
103 if (ready < 0)
104 {
105 if (errno == EINTR) continue;
106 RCLCPP_ERROR_STREAM(
107 rclcpp::get_logger("smacc2"),
108 "[ClRosLaunch2] poll() failed: " << std::generic_category().message(errno));
109 break;
110 }
111 if (ready == 0) continue;
112
113 ssize_t bytesRead = read(fd, buffer.data(), buffer.size());
114 if (bytesRead > 0)
115 {
116 result.append(buffer.data(), static_cast<size_t>(bytesRead));
117 }
118 else if (bytesRead == 0)
119 {
120 RCLCPP_INFO(
121 rclcpp::get_logger("smacc2"), "[ClRosLaunch2] launch process closed its output");
122 break;
123 }
124 else if (errno != EINTR && errno != EAGAIN)
125 {
126 RCLCPP_ERROR_STREAM(
127 rclcpp::get_logger("smacc2"),
128 "[ClRosLaunch2] read() failed: " << std::generic_category().message(errno));
129 break;
130 }
131 }
132
133 rclcpp::sleep_for(2s);
134 if (child.pid > 0)
135 {
136 killGrandchildren(child.pid);
137 rclcpp::sleep_for(2s);
138 }
139
140 int status = 0;
141 pid_t child_pid = child.pid;
142 if (waitpid(child_pid, &status, 0) != -1)
143 {
144 if (WIFEXITED(status))
145 {
146 int exit_status = WEXITSTATUS(status);
147 RCLCPP_INFO(
148 rclcpp::get_logger("smacc2"), "Child process exited with status: %d", exit_status);
149 }
150 else if (WIFSIGNALED(status))
151 {
152 int term_signal = WTERMSIG(status);
153 RCLCPP_WARN(
154 rclcpp::get_logger("smacc2"), "Child process terminated by signal: %d", term_signal);
155 }
156 }
157 else
158 {
159 RCLCPP_ERROR(rclcpp::get_logger("smacc2"), "Error waiting for child process.");
160 }
161
162 // The stream came from fdopen() on our own pipe and the child is reaped: fclose, through
163 // the pointer's deleter, closes the descriptor and frees the FILE. Not pclose().
164 child.pipe.reset();
165
166 RCLCPP_WARN_STREAM(rclcpp::get_logger("smacc2"), "[ClRosLaunch2] RESULT:\n" << result);
167
168 return result;
169 });
170}
171
174
175ProcessInfo runProcess(const char * command)
176{
177 ProcessInfo info{-1, {nullptr, &fclose}}; // PID -1 is the error sentinel
178
179 int pipefd[2]; // File descriptors for the pipe
180
181 if (pipe(pipefd) == -1)
182 {
183 perror("pipe");
184 return info;
185 }
186
187 pid_t pid = fork();
188
189 if (pid == 0)
190 {
191 // Child process
192 close(pipefd[0]); // Close read end in child
193 dup2(pipefd[1], STDOUT_FILENO); // Redirect stdout to pipe
194 close(pipefd[1]); // Close write end in child
195
196 execl("/bin/sh", "/bin/sh", "-c", command, nullptr); // Execute the command
197
198 // execl only returns on error
199 std::cerr << "Error executing command: " << command << std::endl;
200 _exit(1); // Use _exit to skip at exit handlers
201 }
202 else if (pid > 0)
203 {
204 // Parent process
205 close(pipefd[1]); // Close write end in parent
206 info.pipe.reset(fdopen(pipefd[0], "r")); // Open read end as text-mode FILE
207 if (info.pipe == nullptr)
208 {
209 // No stream to read the child through: close the descriptor, stop and reap the child.
210 close(pipefd[0]);
211 kill(pid, SIGTERM);
212 waitpid(pid, nullptr, 0);
213 }
214 else
215 {
216 info.pid = pid;
217 }
218 }
219 else
220 {
221 close(pipefd[0]);
222 close(pipefd[1]);
223 std::cerr << "Error creating child process." << std::endl;
224 }
225
226 return info;
227}
228
230{
231 std::string command = "pgrep -P " + std::to_string(pid);
232 FILE * pipe = popen(command.c_str(), "r");
233
234 if (!pipe)
235 {
236 std::cerr << "Error executing pgrep command." << std::endl;
237 return;
238 }
239
240 char buffer[128];
241 std::string result = "";
242
243 while (fgets(buffer, sizeof(buffer), pipe) != NULL)
244 {
245 result += buffer;
246 }
247
248 pclose(pipe);
249
250 std::istringstream iss(result);
251 pid_t childPid = 0;
252 std::vector<pid_t> childPids;
253
254 while (iss >> childPid)
255 {
256 childPids.push_back(childPid);
257 }
258
259 // Kill child processes before killing the parent process
260 for (const pid_t & child : childPids)
261 {
263 }
264
265 // After killing all children, kill the parent process
266 int res = kill(pid, SIGTERM);
267 if (res == 0)
268 {
269 RCLCPP_FATAL(rclcpp::get_logger("smacc2"), "Killed process %d", pid);
270 }
271}
272
273void killGrandchildren(pid_t originalPid) { killProcessesRecursive(originalPid); }
274} // namespace client_bases
275} // namespace smacc2
static std::future< std::string > executeRosLaunch(const std::string &packageName, const std::string &launchFileName, std::function< bool()> cancelCondition, ClRosLaunch2 *client=nullptr)
void killGrandchildren(pid_t originalPid)
ProcessInfo runProcess(const char *command)