2

I am using systemd to run a shell script at boot, start.sh, that eventually starts main.py, my program’s main Python script.

I would like to record the PID of main.py so it can be programmatically killed later.

I first tried the following, but found that the Python script didn’t stay alive, even though the PID was recorded (note that I’m redirecting error output to a log file).

sudo python main.py 2> >(sudo tee /var/log/app.log) &
echo $1 > /tmp/app.pid

However, when removing the &, the script stays alive, but the PID script never reaches the line where it records the PID.

sudo python main.py 2> >(sudo tee /var/log/app.log)
echo $1 > /tmp/app.pid

How can I run main.py in a way that keeps it alive, but still gives me the PID?

2
  • 3
    in your main.py script you can import os and use os.getpid() to get the process id of your running script. You can then print that out to wherever you'd like to record it. If it's python3, you can print(os.getpid(), file=open("<dir>/file.pid", "a")) for python2 you'd need to open the file first filevar = open("<dir>/file.pid","w") then use filevar.write(os.getpid()) – Fubar May 29 '20 at 19:11
  • Why don't you use systemctl for killing the service? That's what SystemD is for, that we do not search and kill PIDs any more... – Hauke Laging May 30 '20 at 4:24
2

a simple example , that use exec

exec replace the current process executable by another executable .

sudo bash -c ' echo $$ > /var/run/app.pid ; exec python3 -u /tmp/main.py  > /var/log/app.log 2>&1 '

and after you can verify by

cat /var/run/app.pid ; ps -ax -o pid,uname,args | grep "^ *$(cat /var/run/app.pid)"
0

Based on Fubar’s comment that mentioned os.getpid(), I found that os.getppid() achieved what I needed, since the parent thread turned out to be the process I needed to kill:

PID = str(os.getppid())
with open(‘app.pid’, ‘w’) as file:
    file.write(PID)

I then can kill this later in a script with:

sudo kill `cat /tmp/app.pid`

Note that I’ve got to use sudo here since the original python script is run with sudo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.