From d5ca527bfe24bfb47a2577dfb36e6ae050d30ea0 Mon Sep 17 00:00:00 2001
From: Christoph Schmidt <christoph.,schmidt@tugraz.at>
Date: Fri, 1 Dec 2023 18:59:26 +0100
Subject: [PATCH] Minor fixes. fail-check if parent is passed wrongly

---
 examples/example2/ChildProcess2.py        |  4 ++--
 examples/example2/ChildProcessControl2.py |  5 ++++-
 examples/example2/example2.py             |  6 ++++--
 pyproject.toml                            |  2 +-
 requirements.txt                          |  2 ++
 src/cmp/CProcess.py                       |  8 ++++++--
 src/cmp/CProcessControl.py                | 23 ++++++++++++++---------
 7 files changed, 33 insertions(+), 17 deletions(-)
 create mode 100644 requirements.txt

diff --git a/examples/example2/ChildProcess2.py b/examples/example2/ChildProcess2.py
index e8b1a75..837a02c 100644
--- a/examples/example2/ChildProcess2.py
+++ b/examples/example2/ChildProcess2.py
@@ -6,8 +6,8 @@ import cmp
 
 class ChildProcess2(cmp.CProcess):
 
-    def __init__(self, state_queue, cmd_queue, enable_interal_logging):
-        super().__init__(state_queue, cmd_queue, enable_interal_logging=enable_interal_logging)
+    def __init__(self, state_queue, cmd_queue, enable_internal_logging):
+        super().__init__(state_queue, cmd_queue, enable_internal_logging=enable_internal_logging)
         self.logger = None
 
     def postrun_init(self):
diff --git a/examples/example2/ChildProcessControl2.py b/examples/example2/ChildProcessControl2.py
index 50f10cf..b8ad925 100644
--- a/examples/example2/ChildProcessControl2.py
+++ b/examples/example2/ChildProcessControl2.py
@@ -10,7 +10,10 @@ class ChildProcessControl2(cmp.CProcessControl):
 
     def __init__(self, parent, signal_class, enable_internal_logging):
         super().__init__(parent, signal_class, enable_internal_logging=enable_internal_logging)
-        self.register_child_process(ChildProcess2(self.state_queue, self.cmd_queue, enable_interal_logging=enable_internal_logging))
+        self.register_child_process(ChildProcess2(
+            self.state_queue,
+            self.cmd_queue,
+            enable_internal_logging=enable_internal_logging))
 
     @cmp.CProcessControl.register_function()
     def call_without_mp(self, a, b, c=None):
diff --git a/examples/example2/example2.py b/examples/example2/example2.py
index 4f38912..822b1a7 100644
--- a/examples/example2/example2.py
+++ b/examples/example2/example2.py
@@ -30,7 +30,7 @@ class Form(QDialog):
         super().__init__(parent)
 
         mysignals = MySignals()
-        child_con = ChildProcessControl2(self, mysignals, enable_internal_logging=False)
+        child_con = ChildProcessControl2(self, mysignals, enable_internal_logging=True)
 
         mysignals.call_without_mp2_changed.connect(self.updateUI)
 
@@ -50,7 +50,9 @@ class Form(QDialog):
         print("updateUI: ", text)
         self.browser.append("->" + str(text) + "+" + str(text2) + "=" + str(text3))
 
-
+    def closeEvent(self, arg__1):
+        self.destroyed.emit()
+        print("Form destroyed.")
 if __name__ == '__main__':
 
     try:
diff --git a/pyproject.toml b/pyproject.toml
index 9a19b98..e304181 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -8,7 +8,7 @@ description = "A Pyside-to-Process Controll class"
 readme = "README.md"
 requires-python = ">=3.7"
 dependencies = [
-    'pyside6', 'pyyaml'
+    'PySide6', 'rich'
 ]
 classifiers = [
     "Programming Language :: Python :: 3",
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..896f5bd
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,2 @@
+rich
+PySide6
diff --git a/src/cmp/CProcess.py b/src/cmp/CProcess.py
index 6961d9b..6c58c51 100644
--- a/src/cmp/CProcess.py
+++ b/src/cmp/CProcess.py
@@ -10,7 +10,7 @@ import cmp
 
 class CProcess(Process):
 
-    def __init__(self, state_queue: Queue, cmd_queue: Queue, enable_internal_logging=True):
+    def __init__(self, state_queue: Queue, cmd_queue: Queue, enable_internal_logging: bool = False):
         Process.__init__(self)
 
         self._enable_internal_logging = enable_internal_logging
@@ -22,7 +22,7 @@ class CProcess(Process):
 
         self.cmd_queue = cmd_queue
         self.state_queue = state_queue
-        self._kill_flag = Value('i', 1)
+        self._kill_flag = Value('i', 0)
 
     def register_kill_flag(self, kill_flag: Value):
         self._kill_flag = kill_flag
@@ -60,6 +60,8 @@ class CProcess(Process):
         self._internal_logger, self._il_handler = self.create_new_logger(f"{self.__class__.__name__}-Int({os.getpid()})")
         self.logger, self.logger_handler = self.create_new_logger(f"{self.__class__.__name__}({os.getpid()})")
         self.enable_internal_logging(self._enable_internal_logging)
+        self._internal_logger.debug(f"Child process {self.__class__.__name__} started.")
+
         try:
             while self._kill_flag.value:
                 try:
@@ -86,6 +88,8 @@ class CProcess(Process):
                     #    self._internal_logger.info(f"Executing {cmd} in Process Class.\n")
                     #    getattr(self, cmd.func_name)(*cmd.args, **cmd.kwargs)
             self._internal_logger.error(f"Control Process exited. Terminating Process {os.getpid()}")
+            if self._kill_flag.value == 0:
+                self._internal_logger.error(f"Process {os.getpid()} received kill signal!")
 
         except KeyboardInterrupt:
             self._internal_logger.warning(f"Received KeyboardInterrupt! Exiting Process {os.getpid()}")
diff --git a/src/cmp/CProcessControl.py b/src/cmp/CProcessControl.py
index 18672b5..8420e73 100644
--- a/src/cmp/CProcessControl.py
+++ b/src/cmp/CProcessControl.py
@@ -15,16 +15,15 @@ import cmp
 
 class CProcessControl(QObject):
 
-    def __init__(self, kill_child_process_flag: Value,
-                 parent: QObject = None,
+    def __init__(self, parent: QObject = None,
                  signal_class: QObject = None,
                  enable_internal_logging: bool = False):
         super().__init__(parent)
-        self._kill_child_process_flag = kill_child_process_flag
+        #self._kill_child_process_flag = kill_child_process_flag
         self._enable_internal_logging = enable_internal_logging
-
-        if parent is not None:
-            parent.destroyed.connect(self.safe_exit)
+        print(f"Parent: {type(parent)}")
+        if isinstance(parent, QWidget) or isinstance(parent, QWindow):
+            parent.destroyed.connect(lambda: self.safe_exit(reason="Parent destroyed."))
 
         # Register this class as signal class (all signals will be implemented and emitted from this class)
         if signal_class is not None:
@@ -73,6 +72,7 @@ class CProcessControl(QObject):
         return self._child_process_pid
 
     def register_child_process(self, child: cmp.CProcess):
+        self._internal_logger.debug(f"Registering child process {child.__class__.__name__}.")
         self._child = child
         self._child.register_kill_flag(self._child_kill_flag)
         self._child_process_pid = child.pid
@@ -120,11 +120,16 @@ class CProcessControl(QObject):
                 name = getattr(func, '__name__', 'unknown')
                 cmd = cmp.CCommandRecord(name, *args, **kwargs)
                 func(self, *args, **kwargs)
-                self.cmd_queue.put(cmd)
+                try:
+                    self.cmd_queue.put(cmd)
+                except Exception as e:
+                    self._internal_logger.error(f"Error while putting {cmd} into cmd_queue: {e}")
+                    raise e
+
             return get_signature
         return register
-    def safe_exit(self):
-        self._internal_logger.warning(f"Shutting down ProcessControl {os.getpid()}")
+    def safe_exit(self, reason: str = ""):
+        self._internal_logger.warning(f"Shutting down ProcessControl {os.getpid()}. Reason: {reason}")
         self._child_kill_flag.value = 0
 
     def __del__(self):
-- 
GitLab