@@ -75,6 +75,15 @@ void rmw_context_impl_s::graph_sub_data_handler(z_loaned_sample_t * sample, void
75
75
}
76
76
}
77
77
78
+ // The variable is used to identify whether the process is trying to exit or not.
79
+ // The atexit function we registered will set the flag and prevent us from closing
80
+ // Zenoh Session. Zenoh API can't be used in atexit function, because Tokio context
81
+ // is already destroyed. It will cause panic if we do so.
82
+ static bool is_exiting = false ;
83
+ void update_is_exiting () {
84
+ is_exiting = true ;
85
+ }
86
+
78
87
// /=============================================================================
79
88
rmw_context_impl_s::Data::Data (
80
89
std::size_t domain_id,
@@ -97,6 +106,10 @@ rmw_context_impl_s::Data::Data(
97
106
graph_guard_condition_ = std::make_unique<rmw_guard_condition_t >();
98
107
graph_guard_condition_->implementation_identifier = rmw_zenoh_cpp::rmw_zenoh_identifier;
99
108
graph_guard_condition_->data = &guard_condition_data_;
109
+ // This atexit function is registered after ROS initialization,
110
+ // so it should be called before ROS finialization
111
+ // Check https://en.cppreference.com/w/cpp/utility/program/exit
112
+ atexit (update_is_exiting);
100
113
}
101
114
102
115
// /=============================================================================
@@ -171,7 +184,11 @@ rmw_ret_t rmw_context_impl_s::Data::shutdown()
171
184
if (shm_provider_.has_value ()) {
172
185
z_drop (z_move (shm_provider_.value ()));
173
186
}
174
- z_close (z_loan_mut (session_), NULL );
187
+ // Don't touch Zenoh Session if the ROS process is exiting,
188
+ // it will cause panic.
189
+ if (!is_exiting) {
190
+ z_close (z_loan_mut (session_), NULL );
191
+ }
175
192
is_shutdown_ = true ;
176
193
return RMW_RET_OK;
177
194
}
@@ -335,8 +352,12 @@ rmw_context_impl_s::rmw_context_impl_s(
335
352
// /=============================================================================
336
353
rmw_context_impl_s::~rmw_context_impl_s ()
337
354
{
338
- // std::lock_guard<std::recursive_mutex> lock(data_->mutex_);
339
- // z_drop(z_move(data_->session_));
355
+ // Don't touch Zenoh Session if the ROS process is exiting,
356
+ // it will cause panic.
357
+ if (!is_exiting) {
358
+ std::lock_guard<std::recursive_mutex> lock (data_->mutex_ );
359
+ z_drop (z_move (data_->session_ ));
360
+ }
340
361
}
341
362
342
363
// /=============================================================================
0 commit comments