Search This Blog

Wednesday, February 9, 2011

List all files used by a process

To list files used by a process simply type:
ls -l /proc/3456/fd
where 3456 is PID of a process.

To get the PID you can use:
ps -C VBoxHeadless -o pid= 
where VBoxHeadless is you process name.

A script listing processes' opened files. Pass a list of processes in the form of a list to it:
123
1234
432


processLine(){
  line="$@" # get all args
  #  just echo them, but you may need to customize it according to your need
  # for example, F1 will store first field of $line, see readline2 script
  # for more examples
  # F1=$(echo $line | awk '{ print $1 }')
  ls -l /proc/$line/fd
  echo $line
}

### Main script stars here ###
# Store file name
FILE=""

# Make sure we get file name as command line argument
# Else read it from standard input device
if [ "$1" == "" ]; then
   FILE="/dev/stdin"
else
   FILE="$1"
   # make sure file exist and readable
   if [ ! -f $FILE ]; then
   echo "$FILE : does not exists"
   exit 1
   elif [ ! -r $FILE ]; then
   echo "$FILE: can not read"
   exit 2
   fi
fi
# read $FILE using the file descriptors

# Set loop separator to end of line
BAKIFS=$IFS
IFS=$(echo -en "\n\b")
exec 3<&0
exec 0<"$FILE"
while read -r line
do
# use $line variable to process line in processLine() function
processLine $line
done
exec 0<&3

# restore $IFS which was used to determine what the field separators are
IFS=$BAKIFS
exit 0 

No comments:

Post a Comment

If you like this post, please leave a comment :)