Skip to content

Commit b5ac099

Browse files
committed
Avoid touching Zenoh Session while exiting.
Signed-off-by: ChenYing Kuo <[email protected]>
1 parent 5c3d385 commit b5ac099

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

rmw_zenoh_cpp/src/detail/rmw_context_impl_s.cpp

+24-3
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,15 @@ void rmw_context_impl_s::graph_sub_data_handler(z_loaned_sample_t * sample, void
7575
}
7676
}
7777

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+
7887
///=============================================================================
7988
rmw_context_impl_s::Data::Data(
8089
std::size_t domain_id,
@@ -97,6 +106,10 @@ rmw_context_impl_s::Data::Data(
97106
graph_guard_condition_ = std::make_unique<rmw_guard_condition_t>();
98107
graph_guard_condition_->implementation_identifier = rmw_zenoh_cpp::rmw_zenoh_identifier;
99108
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);
100113
}
101114

102115
///=============================================================================
@@ -171,7 +184,11 @@ rmw_ret_t rmw_context_impl_s::Data::shutdown()
171184
if (shm_provider_.has_value()) {
172185
z_drop(z_move(shm_provider_.value()));
173186
}
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+
}
175192
is_shutdown_ = true;
176193
return RMW_RET_OK;
177194
}
@@ -335,8 +352,12 @@ rmw_context_impl_s::rmw_context_impl_s(
335352
///=============================================================================
336353
rmw_context_impl_s::~rmw_context_impl_s()
337354
{
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+
}
340361
}
341362

342363
///=============================================================================

0 commit comments

Comments
 (0)