70 std::string packageName, std::string launchFileName, std::function<
bool()> cancelCondition,
76 [packageName, launchFileName, cancelCondition, client]()
78 RCLCPP_WARN_STREAM(rclcpp::get_logger(
"smacc2"),
"[ClRosLaunch2] Starting ros launch thread");
80 std::stringstream cmd;
81 cmd <<
"ros2 launch " << packageName <<
" " << launchFileName;
82 std::array<char, 128> buffer;
89 throw std::runtime_error(
"popen() failed!");
91 if (client !=
nullptr)
96 int fd = fileno(child.pipe);
98 int flags = fcntl(fd, F_GETFL, 0);
99 fcntl(fd, F_SETFL, flags | O_NONBLOCK);
101 bool cancelled =
false;
106 cancelled = cancelCondition();
107 size_t bytesRead = fread(buffer.data(), 1, buffer.size(), child.pipe);
111 result.append(buffer.data(), bytesRead);
113 else if (bytesRead == 0)
116 std::this_thread::sleep_for(
117 std::chrono::milliseconds(100));
122 RCLCPP_ERROR(rclcpp::get_logger(
"smacc2"),
"Error de lectura en pipe");
127 rclcpp::sleep_for(2s);
131 rclcpp::sleep_for(2s);
135 pid_t child_pid = child.pid;
136 if (waitpid(child_pid, &status, 0) != -1)
138 if (WIFEXITED(status))
140 int exit_status = WEXITSTATUS(status);
142 rclcpp::get_logger(
"smacc2"),
"Child process exited with status: %d", exit_status);
144 else if (WIFSIGNALED(status))
146 int term_signal = WTERMSIG(status);
148 rclcpp::get_logger(
"smacc2"),
"Child process terminated by signal: %d", term_signal);
153 RCLCPP_ERROR(rclcpp::get_logger(
"smacc2"),
"Error waiting for child process.");
157 close(child.pipe->_fileno);
159 RCLCPP_WARN_STREAM(rclcpp::get_logger(
"smacc2"),
"[ClRosLaunch2] RESULT:\n" << result);
216 std::string command =
"pgrep -P " + std::to_string(pid);
217 FILE * pipe = popen(command.c_str(),
"r");
221 std::cerr <<
"Error executing pgrep command." << std::endl;
226 std::string result =
"";
228 while (fgets(buffer,
sizeof(buffer), pipe) != NULL)
235 std::istringstream iss(result);
237 std::vector<pid_t> childPids;
239 while (iss >> childPid)
241 childPids.push_back(childPid);
245 for (
const pid_t & child : childPids)
251 int res = kill(pid, SIGTERM);
254 RCLCPP_FATAL(rclcpp::get_logger(
"smacc2"),
"Killed process %d", pid);