65 std::string packageName, std::string launchFileName, std::function<
bool()> cancelCondition,
70 [packageName, launchFileName, cancelCondition, client]()
72 RCLCPP_WARN_STREAM(rclcpp::get_logger(
"smacc2"),
"[ClRosLaunch2] Starting ros launch thread");
74 std::stringstream cmd;
75 cmd <<
"ros2 launch " << packageName <<
" " << launchFileName;
76 std::array<char, 128> buffer;
83 throw std::runtime_error(
"popen() failed!");
85 if (client !=
nullptr)
90 int fd = fileno(child.pipe);
92 int flags = fcntl(fd, F_GETFL, 0);
93 fcntl(fd, F_SETFL, flags | O_NONBLOCK);
95 bool cancelled =
false;
100 cancelled = cancelCondition();
101 size_t bytesRead = fread(buffer.data(), 1, buffer.size(), child.pipe);
105 result.append(buffer.data(), bytesRead);
107 else if (bytesRead == 0)
110 std::this_thread::sleep_for(std::chrono::milliseconds(100));
115 RCLCPP_ERROR(rclcpp::get_logger(
"smacc2"),
"Error reading from pipe");
120 rclcpp::sleep_for(2s);
124 rclcpp::sleep_for(2s);
128 pid_t child_pid = child.pid;
129 if (waitpid(child_pid, &status, 0) != -1)
131 if (WIFEXITED(status))
133 int exit_status = WEXITSTATUS(status);
135 rclcpp::get_logger(
"smacc2"),
"Child process exited with status: %d", exit_status);
137 else if (WIFSIGNALED(status))
139 int term_signal = WTERMSIG(status);
141 rclcpp::get_logger(
"smacc2"),
"Child process terminated by signal: %d", term_signal);
146 RCLCPP_ERROR(rclcpp::get_logger(
"smacc2"),
"Error waiting for child process.");
150 close(child.pipe->_fileno);
152 RCLCPP_WARN_STREAM(rclcpp::get_logger(
"smacc2"),
"[ClRosLaunch2] RESULT:\n" << result);
207 std::string command =
"pgrep -P " + std::to_string(pid);
208 FILE * pipe = popen(command.c_str(),
"r");
212 std::cerr <<
"Error executing pgrep command." << std::endl;
217 std::string result =
"";
219 while (fgets(buffer,
sizeof(buffer), pipe) != NULL)
226 std::istringstream iss(result);
228 std::vector<pid_t> childPids;
230 while (iss >> childPid)
232 childPids.push_back(childPid);
236 for (
const pid_t & child : childPids)
242 int res = kill(pid, SIGTERM);
245 RCLCPP_FATAL(rclcpp::get_logger(
"smacc2"),
"Killed process %d", pid);