Skip to content

Commit

Permalink
Don't close Zenoh session while the process is terminating.
Browse files Browse the repository at this point in the history
Signed-off-by: ChenYing Kuo <[email protected]>
  • Loading branch information
evshary committed Dec 16, 2024
1 parent dd82e84 commit ed041b2
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
9 changes: 8 additions & 1 deletion rmw_zenoh_cpp/src/detail/zenoh_utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@

namespace rmw_zenoh_cpp
{
// Initialize the static variable in ZenohSession
std::once_flag ZenohSession::initFlag;
std::atomic<bool> ZenohSession::is_exiting(false);

/// Loan the zenoh session.
///=============================================================================
const z_loaned_session_t * ZenohSession::loan()
Expand All @@ -35,7 +39,10 @@ const z_loaned_session_t * ZenohSession::loan()
///=============================================================================
ZenohSession::~ZenohSession()
{
z_close(z_loan_mut(inner_), NULL);
// Don't close Zenoh session while the process is terminating
if (!is_exiting.load()) {
z_close(z_loan_mut(inner_), NULL);
}
}

///=============================================================================
Expand Down
19 changes: 18 additions & 1 deletion rmw_zenoh_cpp/src/detail/zenoh_utils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@

#include <zenoh.h>

#include <atomic>
#include <chrono>
#include <functional>
#include <mutex>
#include <optional>

#include "rmw/types.h"
Expand All @@ -32,12 +34,27 @@ class ZenohSession final
{
public:
ZenohSession(z_owned_session_t sess)
: inner_(sess) {}
: inner_(sess) {
std::call_once(initFlag, [] {
// This atexit function should be triggered before ZenohSession destruction
// Refer to https://en.cppreference.com/w/cpp/utility/program/exit
atexit([] {
ZenohSession::is_exiting.store(true);
});
});
}
const z_loaned_session_t * loan();
~ZenohSession();

private:
z_owned_session_t inner_;
// Used to ensure atexit function is only registered once.
static std::once_flag initFlag;
// The variable is used to identify whether the process is trying to exit or not.
// The atexit function we registered will set the flag and prevent us from closing
// Zenoh Session. Zenoh API can't be used in atexit function, because Tokio context
// is already destroyed. It will cause panic if we do so.
static std::atomic<bool> is_exiting;
};

///=============================================================================
Expand Down

0 comments on commit ed041b2

Please sign in to comment.