Search code examples
pythonraspberry-pifbi

cannot kill fbi process started from a python script


This python code runs fbi in an infinite loop even though there is a trap for ctrl-C

import os
var = 1
try:
    while var == 1:
        os.system("sleep 5; kill $(pgrep fbi); sudo fbi -a image1.jpg")
except KeyboardInterrupt:
    kill $(pgrep fbi)
    pass

I hit ctrl-C, the screen blinks and image1 is back up. Now I know python is behaving properly because this code exits with ctrl-C

import os
var = 1
x = 0
try:
    while var == 1:
        x += 1
        print x
except KeyboardInterrupt:
    pass

and when I open another virtual console with alt-F2, login and try

sudo kill -9 fbi

of course the python process just restarts it. I have to kill the python process. The reason for doing this is to use fbi to display images in a python process that does image processing on a raspberry pi that is NOT running x windows, ubuntu, etc. It is console only.

Why doesn't fbi respect the keyboard interrupt?


Solution

  • kill $(pgrep fbi) is not Python syntax, you can't put it directly into the Python script. You need to execute it as a shell command, just like you did when you were starting up fbi.

    import os
    var = 1
    try:
        while var == 1:
            os.system("sleep 5; sudo pkill fbi; sudo fbi -a image1.jpg")
    except KeyboardInterrupt:
        os.system("sudo pkill fbi")
    

    Also, if you run fbi with sudo, you need to use sudo when killing it as well. An ordinary user can't kill a process being run by root.

    It's better to use pkill fbi instead of kill $(pgrep fbi). The latter will get an error if pgrep doesn't find any processes, because it will execute kill with no arguments.