Logging before a fatal exit

asked 2020-06-10 08:10:41 -0600

Ekaradon gravatar image

updated 2020-06-11 02:27:18 -0600

For example I want to have a ROS node which opens serial port and reads some data. Here's the code.

#include "ros/ros.h"
#include <fcntl.h>      // Introducing `open` system call.

int main(int argc, char **argv) {
    ros::init(argc, argv, "serial_listener");
    ros::NodeHandle nh;

    ROS_INFO("Trying to open device %s", argv[1]);
    int uart_fd = open(argv[1], O_RDWR | O_NOCTTY | O_SYNC);
    ROS_ASSERT_MSG(uart_fd >= 0, "Failed to open device %s", argv[1]);

    while (ros::ok()) {
        // do something
    } 
}

If I run command rosrun <package> <node> /dev/serialx and /dev/serialx is not a valid device, the output in console would be

[ INFO] [1591786226.001258952]: Trying to open device /dev/serialx
[FATAL] [1591786226.005150306]: ASSERTION FAILED
    file = xx/xx/xx/xx.cc
    line = 10
    cond = uart_fd >= 0
    message = 
[FATAL] [1591786226.005387754]: Failed to open device /dev/serialx
[FATAL] [1591786226.005461972]:

However, these are NOT saved to rosout.log file.

So is there any way to have these lines saved into log file when fatal error?

Related question: Is there a common design pattern for fatal exit?


If I add some delay after declaring node handle, and use ROS_FATAL_COND rather than ROS_ASSERT_MSG, then all output can be logged.

#include "ros/ros.h"
#include <fcntl.h>      // Introducing `open` system call.

int main(int argc, char **argv) {
    ros::init(argc, argv, "serial_listener");
    ros::NodeHandle nh;
    ros::Duration(0.5).sleep();    // <--

    ROS_INFO("Trying to open device %s", argv[1]);
    int uart_fd = open(argv[1], O_RDWR | O_NOCTTY | O_SYNC);
    ROS_FATAL_COND(uart_fd < 0, "Failed to open device %s", argv[1]);    // <--

    while (ros::ok()) {
        // do something
    } 
}

So is there any better method than a hard-coded delay ros::Duration(0.5).sleep()? I tried to use ros::isStarted() and ros::isInitialized(), but it seems they don't work.

edit retag flag offensive close merge delete