From f71635f8f8f361bb54d66075e7c0bc2ee02948bb Mon Sep 17 00:00:00 2001
From: P-A Loizeau <p.-a.loizeau@gsi.de>
Date: Mon, 30 Jan 2023 16:06:50 +0100
Subject: [PATCH] [MQ] In DigiSink device, fix crash on Term transition with
 ODC/DDS

---
 MQ/mcbm/CbmDeviceDigiEventSink.cxx | 24 ++++++++++++++++--------
 MQ/mcbm/CbmDeviceDigiEventSink.h   |  1 +
 2 files changed, 17 insertions(+), 8 deletions(-)

diff --git a/MQ/mcbm/CbmDeviceDigiEventSink.cxx b/MQ/mcbm/CbmDeviceDigiEventSink.cxx
index b2d6a15cab..ddedd7a31d 100644
--- a/MQ/mcbm/CbmDeviceDigiEventSink.cxx
+++ b/MQ/mcbm/CbmDeviceDigiEventSink.cxx
@@ -759,6 +759,16 @@ bool CbmDeviceDigiEventSink::SendHistograms()
   return true;
 }
 
+//--------------------------------------------------------------------//
+void CbmDeviceDigiEventSink::PostRun()
+{
+  // Needed to avoid due to other end of ZMQ channel being already gone if called during Finish/destructor
+  if (kTRUE == fbFillHistos) {
+    SendHistograms();
+    fLastPublishTime = std::chrono::system_clock::now();
+  }  // if( kTRUE == fbFillHistos )
+}
+
 //--------------------------------------------------------------------//
 CbmDeviceDigiEventSink::~CbmDeviceDigiEventSink()
 {
@@ -787,14 +797,12 @@ void CbmDeviceDigiEventSink::Finish()
   LOG(info) << "Still buffered TS " << fmFullTsStorage.size() << " and still buffered empties "
             << fvulMissedTsIndices.size();
 
-  if (kTRUE == fbFillHistos) {
-    SendHistograms();
-    fLastPublishTime = std::chrono::system_clock::now();
-  }  // if( kTRUE == fbFillHistos )
-
-  ChangeState(fair::mq::Transition::Stop);
-  std::this_thread::sleep_for(std::chrono::milliseconds(3000));
-  ChangeState(fair::mq::Transition::End);
+  if (fair::mq::State::Running == GetCurrentState()) {
+    /// Force state transitions only if not already done by ODC/DDS!
+    ChangeState(fair::mq::Transition::Stop);
+    std::this_thread::sleep_for(std::chrono::milliseconds(3000));
+    ChangeState(fair::mq::Transition::End);
+  }
 
   fbFinishDone = kTRUE;
 }
diff --git a/MQ/mcbm/CbmDeviceDigiEventSink.h b/MQ/mcbm/CbmDeviceDigiEventSink.h
index 0d617899f4..8c016409bc 100644
--- a/MQ/mcbm/CbmDeviceDigiEventSink.h
+++ b/MQ/mcbm/CbmDeviceDigiEventSink.h
@@ -93,6 +93,7 @@ protected:
   bool HandleMissTsData(FairMQMessagePtr&, int);
   bool HandleData(FairMQParts&, int);
   bool HandleCommand(FairMQMessagePtr&, int);
+  virtual void PostRun();
 
 private:
   /// Constants
-- 
GitLab