0

I'm trying to use the pidof command to see my script is already running as I only want this executable if the script is not already running, however, it seems the pidof command is not returning the pid of the script using the name which is displayed in ps -ef output. Instead it is masking this name as either /usr/bin/python or /bin/su. Can someone shed some light on what is going on and how I can run pidof 'script.py -v' to see if the script is running or not?

[root@cloud proc]# pidof python /some/dir/script.py -v
> pidof: invalid options on command line!

[root@cloud proc]# pidof "python /some/dir/script.py -v"
>

[root@cloud proc]# pidof "su - user -c python /some/dir/script.py -v"
> 

[root@cloud proc]# ps -ef | grep script.py
> root      5409 31739  0 13:07 pts/1    00:00:00 su - user -c python /some/dir/script.py -v
> user      5414  5409 96 13:07 ?        01:00:40 python /some/dir/script.py -v

[root@cloud proc]# ls -l /proc/5409/exe
> lrwxrwxrwx. 1 root root 0 Oct 13 14:04 /proc/5409/exe -> /bin/su

[root@cloud proc]# ls -l /proc/5414/exe
> lrwxrwxrwx. 1 user user 0 Oct 13 14:04 /proc/5414/exe -> /usr/bin/python

[root@cloud proc]# pidof /bin/su
> 31715 6308 5409

[root@cloud proc]# pidof /usr/bin/python
> 5414
Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
Alan Kavanagh
  • 351
  • 5
  • 17

1 Answers1

3

pidof doesn't offer a way to specify /path/to/script to match commands of the form interpretername /path/to/script. It always looks at the filename of the executable listed in the /proc/pid/stat file.

But it will work if your script begins with a shebang #! and if you invoke the script with /path/to/script.

As an alternative, most GNU/Linux systems offer a pgrep command, which can match all or part of a command line. In your example, you can use

pgrep -x -f 'python /some/dir/script.py -v'

This will match the exact command line. If you want to match a partial command line, you can do something like

pgrep -x -f 'python /some/dir/script.py .*'

You can omit the -x to put an implicit .* at the beginning and end of the pattern, but this will also match your su - user -c python /some/dir/script.py -v process.

As you mentioned in comments, a better way to assure your command doesn't run multiple instances at the same time is to use file locking, such as fcntl.flock.

Mark Plotnick
  • 24,913
  • 2
  • 59
  • 81