musasabi musasabi -4 years ago 87
Linux Question

Methods to restart died process

There's a little app named logivew that I'm writing a script to monitor, along with some other tasks. In the main while loop (which will exit when the app I'm most concerned about closes), I check to see if logview needs restarting. The code I have presently is roughly as follows:

#a good old global
logview = "/usr/bin/logview"


#a function that starts logview:
port = 100
log_file = "/foo/bar"
logview_process = subprocess.Popen([logview, log_file, port],
stdout = subprocess.DEVNULL,
stderr = subprocess.STDOUT)

#a separate function that monitors in the background:
while True:
time.sleep(1)

logview_status = 0

try:
logview_status = psutil.Process(logview_process.pid).status()
except psutil.NoSuchProcess:
pass

if(logview_status == psutil.STATUS_STOPPED or
logview_status == psutil.STATUS_ZOMBIE or
logview_status == psutil.STATUS_DEAD or
logview_status == 0):
print("Logview died; restarting")

logview_cli_list = [logview]
logview_cli_list.extend(logview_process.args)

logview_process = subprocess.Popen(logview_cli_list,
stdout = subprocess.DEVNULL,
stderr = subprocess.STDOUT)

if(some_other_condition): break


However, if I test-kill logview, the condition triggers and I do see the printed message, but then I see it again, and again, and again. It seems that the condition triggers every single iteration of the loop if logview does die. And, it never does get restarted properly.

So clearly... I'm doing something wrong. =)

Any help (or better methods!) would be greatly appreciated.

Answer Source

I don't know your logview program but the problem is here:

logview_cli_list = [logview]
logview_cli_list.extend(logview_process.args)

When you're creating the argument list, you're putting logview twice in your command, because logview_process.args also contains the name of the launched command, so the program probably fails immediately because of bad args, and is run again and again...

The fix is then obvious:

logview_cli_list = logview_process.args

a better fix would be to create the process in the loop if a given flag is set and set the flag at the start. When process dies, set the flag to trigger the process creation again. Would have avoided this copy/almost paste mistake.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download