2

So I am writing a bash script which will run through all of the process ids in /proc/[pid] and read the executable that was used to run it.

From what I have had a looked at, the /proc filesystem contains the /proc/[pid]/exe symbolic link. Within the bash script I am trying work out how to read the value of "readlink /proc/[pid]/exe" to check if (deleted) or nothing is returned to find out whether the original executable exists on the disk or not.

Is there a way of doing this, so far I have?

#!/bin/bash
pid = "0"

while [ $pid -lt 32769 ]
do
    if [-d /proc/$pid]; then
        if [-f /proc/$pid/exe]; then
            echo $pid
            readlink /proc/$pid/exe
        fi
    fi
    pid = $[$pid+1]
done

This fails to work and always returns nothing.I am trying to list all of the processes that no longer have their executables available on disk.

Jahid
  • 21,542
  • 10
  • 90
  • 108
DesiBoyz
  • 130
  • 2
  • 14

4 Answers4

0

I've updated your script to make it work. Notice that -f checks whether a file name represents a regular file. I would return false for a symbolic link:

pid="0"
while [ $pid -lt 32769 ]
do
    if [ -d /proc/$pid ]; then
        if [ -h /proc/$pid/exe ]; then
            echo $pid
            readlink /proc/$pid/exe
        fi
    fi
    pid=$[$pid+1]
done
OrenD
  • 1,751
  • 13
  • 12
0

you can read returned value after any command in shell by printing $? variable:

 readlink
 echo $?

if link is invalid, $? will be bigger than 0.

however if link exist and actual file is deleted, you can use something like:

ls `readlink somelink`
Amir H
  • 482
  • 4
  • 10
0

Will this work for you?

#!/bin/bash

for i in $(ls /proc | awk '/^[[:digit:]]+/{print $1}'); do
  if [ -h /proc/$i/exe ]; then
    echo -n "$i: "
    if readlink /proc/$i/exe >/dev/null 2>&1 ; then
      echo "executable exists"
    else
      echo "executable not found"
    fi
  fi
done
Brian Showalter
  • 4,321
  • 2
  • 26
  • 29
  • 1
    Why not `for i in /proc/[0-9]*/exe; do` ? – caf Jun 02 '15 at 08:20
  • This worked for me, except for the for loop. I finally went with the while loop. 'while [ $pid -lt 32769 ]'. Although this method does not work for deleted executables. – DesiBoyz Jun 02 '15 at 09:55
  • Good one, @caf! Just didn't think of that method. @DesiBoyz, out of curiosity, what was wrong with the for loop? – Brian Showalter Jun 02 '15 at 12:44
0
   readlink -f `ls --dereference /proc/$pid/exe`
  • Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others. – IKavanagh Oct 03 '15 at 15:44