views:

45

answers:

2

Hello,

I'm executing a SSH process like so:

checkIn()
sshproc = subprocess.Popen([command], shell=True)
exit = os.waitpid(sshproc.pid, 0)[1]
checkOut()

Its important that the process form checkIn() and checkOut() actions before and after these lines of code. I have a test case that involves that I exit the SSH session by closing the terminal window manually. Sure enough, my program doesn't operate correctly and checkOut() is never called in this case. Can someone give me a pointer into what I can look in to fix this bug?

Let me know if any other information would helpful.

Thanks!

+1  A: 

The Python process would normally execute in the same window as the ssh subprocess, and therefore be terminated just as abruptly when you close that window -- before getting a chance to execute checkOut. To try and ensure that a function gets called at program exit (though for sufficiently-abrupt terminations, depending on your OS, there may be no guarantees), try Python standard library module atexit.

Alex Martelli
Very neat module, but didn't solve the problem. Thank you for the post!
gnucom
@gnucom, if you need to ensure some code's execution when your process terminates very abruptly (worst case, via a `kill -9`... or even a HW fault!), you need, by definition, to execute that code in a _separate_ ("daemon") process -- a "watchdog" that does nothing but wait for the main process's untimely exit and, if and when that happens, runs said code. Being in a different process of course means architectural constrains on what you can and cannot do, but (for sufficiently abrupt terminations) it's the only game in town:-(.
Alex Martelli
@Alex, thank you for the design suggestion. I think that is what I will end up doing because `kill -9` is essentially the test case that I am stuck with.
gnucom
+1  A: 

Perhaps all you need is a try ... finally block?

try:
    checkIn()
    sshproc = subprocess.Popen([command], shell=True)
    exit = os.waitpid(sshproc.pid, 0)[1]
finally:
    checkOut()

Unless the system crashes, the process receives SIGKILL, etc., checkOut() should be called.

llasram