diff --git a/rmw_zenoh_cpp/src/detail/rmw_context_impl_s.cpp b/rmw_zenoh_cpp/src/detail/rmw_context_impl_s.cpp index 3cbc460f..2cff857c 100644 --- a/rmw_zenoh_cpp/src/detail/rmw_context_impl_s.cpp +++ b/rmw_zenoh_cpp/src/detail/rmw_context_impl_s.cpp @@ -100,9 +100,13 @@ class rmw_context_impl_s::Data final RMW_SET_ERROR_MSG("Error setting up zenoh session"); throw std::runtime_error("Error setting up zenoh session."); } + atexit(update_is_exiting); auto close_session = rcpputils::make_scope_exit( [this]() { - z_close(z_loan_mut(session_), NULL); + // Don't touch Zenoh Session if the ROS process is exiting, it will cause panic. + if (!is_exiting) { + z_close(z_loan_mut(session_), NULL); + } }); // Verify if the zenoh router is running if configured. @@ -265,10 +269,13 @@ class rmw_context_impl_s::Data final // to avoid an AB/BA deadlock if shutdown is racing with graph_sub_data_handler(). } - // Close the zenoh session - if (z_close(z_loan_mut(session_), NULL) != Z_OK) { - RMW_SET_ERROR_MSG("Error while closing zenoh session"); - return RMW_RET_ERROR; + // Don't touch Zenoh Session if the ROS process is exiting, it will cause panic. + if (!is_exiting) { + // Close the zenoh session + if (z_close(z_loan_mut(session_), NULL) != Z_OK) { + RMW_SET_ERROR_MSG("Error while closing zenoh session"); + return RMW_RET_ERROR; + } } return RMW_RET_OK; }