Home > Blockchain >  How to check if specific executable has a live process for specific user in bash?
How to check if specific executable has a live process for specific user in bash?

Time:08-31

im trying to check if specific executable has a live process for specific user

so i tried :

lsof $(which python3) -u username

and its not concidering the -u

im getting a list of all python live processes for ALL of the users

i also tried use -a but its not working

CodePudding user response:

If lsof doesn't work, you can always reimplement it yourself.

#!/usr/bin/env bash
#              ^^^^- MUST be bash, not sh

user=nobody
target_exe=/usr/bin/python3

while IFS=' ' read -r -d '' proc_name exe_link; do
  pid=${proc_name%/exe}
  if [[ $exe_link = "$target_exe" ]]; then
    echo "$pid"
  fi
done < <(
  find /proc -mindepth 2 -maxdepth 2 \
    '!' -user "$user" -prune -o \
    '(' -name exe -path '/proc/[[:digit:]]*' -printf '%P %l\0' ')')

Note that, for this tool as well as for lsof itself, you need to be running with enough permissions to access the relevant content in procfs.

  • Related