# HG changeset patch
# User Andrey Skvortsov <andrej.skvortzov@gmail.com>
# Date 1461837957 -10800
# Node ID d7f474d1021083afeb5dda918a04b19b3f8d6521
# Parent  b9b8978dbc9d22bbf5140835bcd5f1aa11efca64
fix issue with sometimes wrong return code of ProcessLogger


As a result of wrong return code Beremiz gives folowing traceback:
Traceback (most recent call last):
  File "./Beremiz.py", line 850, in OnMenu
    getattr(self.CTR, method)()
  File "/home/developer/WorkData/PLC/beremiz/beremiz/ProjectController.py", line 925, in _Build
    IECGenRes = self._Generate_SoftPLC()
  File "/home/developer/WorkData/PLC/beremiz/beremiz/ProjectController.py", line 568, in _Generate_SoftPLC
    return self._Compile_ST_to_SoftPLC()
  File "/home/developer/WorkData/PLC/beremiz/beremiz/ProjectController.py", line 661, in _Compile_ST_to_SoftPLC
    C_files.remove("POUS.c")
ValueError: list.remove(x): x not in list

The problem is that both threads (for reading stdout and stderr) call self.Proc.poll(),
that updates internal returncode field. This call is done without any locking and the first thread gets correct result,
but other gets 0 as retval. If 0 gets thread, that afterwards calls callback finish, then wrong return code is returned
to the parent. Now only the thread with a callback polls for the return code, other thread just checked local value.

Additionally function spin() waits now until all threads finish reading their pipes, so the results are always correct.

diff -r b9b8978dbc9d -r d7f474d10210 util/ProcessLogger.py
--- a/util/ProcessLogger.py	Thu Apr 28 12:58:58 2016 +0300
+++ b/util/ProcessLogger.py	Thu Apr 28 13:05:57 2016 +0300
@@ -49,11 +49,12 @@
     def run(self):
         outchunk = None
         self.retval = None
-        while outchunk != '' and not self.killed :
-            outchunk = self.fd.readline()
-            if self.callback : self.callback(outchunk)
         while self.retval is None and not self.killed :
-            self.retval = self.Proc.poll()
+            if self.endcallback:
+                self.retval = self.Proc.poll()
+            else:
+                self.retval = self.Proc.returncode
+                
             outchunk = self.fd.readline()
             if self.callback : self.callback(outchunk)
         while outchunk != '' and not self.killed :
@@ -205,5 +206,7 @@
 
     def spin(self):
         self.finishsem.acquire()
+        self.outt.join()
+        self.errt.join()
         return [self.exitcode, "".join(self.outdata), "".join(self.errdata)]