Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't close Zenoh session while the process is terminating. #339

Draft
wants to merge 2 commits into
base: rolling
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -26,6 +26,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 @@ -37,7 +41,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
20 changes: 19 additions & 1 deletion rmw_zenoh_cpp/src/detail/zenoh_utils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@
#include <zenoh.hxx>

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

#include "rmw/types.h"
Expand All @@ -33,12 +35,28 @@ 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