1

I am trying to build a nice service bash script for a custom service I built, my problem is that I need to identify if the process is running armed with the path to the file only.

From all my googling I have found the answer on how to find the path of a PID but I need the exact opposite.

Let's say my executable is located in /home/monitor/script.py

It is executed like this: python /home/monitor/script.py

Armed with this how would I be able to find the process ID if it is running?

3 Answers 3

1

Try using ps to look for the script by name:

ps -f -C python | grep /home/monitor/script.py

The -C flag tells ps to list processes named "python", the -f gives "full" output including the command line, and the grep picks out the right python process. The pid is the second field in the line.

2
  • 1
    And in order to get just the PID I added this at the end: | awk '{print $1}' Feb 11, 2013 at 13:54
  • In fact, ps -C can also search using the script name (on this Debian system, at least), so you would be able to avoid the grep. Feb 11, 2013 at 15:42
0

(Assuming Linux, you might be able to parse something out of /proc - but, don't)

If your script needs to know if it's already running, have it write a PID somewhere when it runs. Then, your script can look in That Place when it starts to see if it's already running or not.

This of course assumes that you don't want to run more than one instance at once; if you do, have a configurable path-to-PID-file which you pass on the command line, or something similar.

2
  • One instance is enough, problem comes in development when experimenting and you get crashes and such. The pid file will be left in place and the bash will presume it running. I need a sure way of knowing. I am experimenting with ps but I can't just get it. It needs to be based on path as there might be other scripts running files with the name. I have had the misfortune of having a Apache path that contained the same name run a pipe via cronolog and that got snagged by ps and made my bash script report running when in fact it was not. Feb 11, 2013 at 11:05
  • Well, you don't just check that the file exists, you also read the contents and see whether the PID it contains is actually a running instance of your program.
    – nickgrim
    Feb 11, 2013 at 14:04
0

A bash command to find out python(2.7) processes:

$ lsof | awk '$9 ~ /^\/usr\/lib\/python2\.7/ {print $0}'

You can modify the command above from the output you get. I am getting varying results here.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .