From 71dc2a6de399861d6a927244a09f45c491b2127a Mon Sep 17 00:00:00 2001 From: Romain Reignier Date: Wed, 4 Mar 2026 17:17:38 +0100 Subject: [PATCH] When creating a process, set the FD_CLOEXEC flag on the master PTY To avoid a leak of the PTY file descriptor in the child process, the ROS Node. This allows to close the master fd in the child process after execvp() is executed. From man fcntl: > FD_CLOEXEC, the close-on-exec flag. If the FD_CLOEXEC bit is set, > the file descriptor will automatically be closed during a successful > execve(2). Before this, the child processes (the shim, then the ROS node) inherited all the `master` and `stderr_master` file descriptors of the other already-running nodes from the parent process. For example, with a launch file with 10 nodes, running `lsof -p $PID` with the pid of the nodes, there was a growing number of `/dev/ptmx` lines for the ROS nodes process. While when launched with roslaunch, there is node. Command used: `sudo lsof -p $PID | grep ptmx | wc -l` | Node number | Number of /dev/ptmx | |-------------|---------------------| | 1 | 0 | | 2 | 2 | | 3 | 4 | | 4 | 6 | | 10 | 18 | With this fix, the number is always zero. --- rosmon_core/src/monitor/node_monitor.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rosmon_core/src/monitor/node_monitor.cpp b/rosmon_core/src/monitor/node_monitor.cpp index 2568a55a..9ccf1dcb 100644 --- a/rosmon_core/src/monitor/node_monitor.cpp +++ b/rosmon_core/src/monitor/node_monitor.cpp @@ -717,6 +717,10 @@ std::pair NodeMonitor::createPTY() if(openpty(&master, &slave, nullptr, nullptr, nullptr) == -1) throw error("Could not open pseudo terminal for child process: {}", strerror(errno)); + // Mark master as close-on-exec so it is not inherited by child processes + if(fcntl(master, F_SETFD, FD_CLOEXEC) == -1) + throw error("Could not set close-on-exec flag for PTY master: {}", strerror(errno)); + // On Linux, a new unix98 pty is initialized with the output flag ONLCR set, // which converts \n to \r\n // Disable this bahavior by clearing the flag