Finding process IDs with fuser

The fuser process is a handy command for getting information about processes that are using particular files. I discovered this command quite a few years ago and rely on it when I need to unmount a file system, find out that it's in use and then need to figure out why.

Fuser doesn't only come in handy when you need to unmount a file system, however. It's also useful command for many other situations in which you need to figure out who is using some particular file or command.

To get a quick look at how easily fuser can provide a list of process IDs associated with some particular resource, try running the commands included in this bash script:

#!/bin/bash

if [ $# == 0 ]; then
    echo -n "file> "
    read FILE
else
    FILE=$1
fi

PROCIDS=`fuser $FILE 2>/dev/null`
echo $PROCIDS

Stripping away standard error in this script removes the letter codes that indicate how each file is being used by each of the processes (see table below), but if the process ID is all you need for further processing, ignoring the letter codes can simplify the process of preparing a list of process IDs.

c     Indicates that the process is using the  file  as  its current directory.

m     Indicates that the process is using a file mapped with mmap(2). See  mmap(2) for details.

o     Indicates that the process is using  the  file  as  an open file.

r     Indicates that the process is using the  file  as  its root directory.

t     Indicates that the process is using the  file  as  its text file.

y     Indicates that the process is using the  file  as  its controlling terminal.

To generate a list of which processes are using bash right now, you could just type "showUsers bash":

# showUsers /bin/bash
7998 7995 2043 2042 2041 962 28488 28487 5159 5157

If you're looking for bash usage, of course, you're going to find the process ID associated with running the script in the list! You could add this line to the end of the script to make this clear:

echo I am $$

Your output might then look like this:

showUsers bash
8246 8243 2043 2042 2041 962 28488 28487 5159 5157
I am 8243

You could also just exclude your script's process ID in later processing if you're concerned that it will trip over itself in searching for other file users.

for PID in `echo $PROCIDS`
do
    if [ $PID != $$ ]; then
        echo $PID
	...
    fi
done

Using fuser instead is ps, grep and awk commands to find process users is far simpler and more accurate than "ps -ef | grep FILE | awk '{print $2}'" commands and works with files as well processes.

Top 10 Hot Internet of Things Startups
Join the discussion
Be the first to comment on this article. Our Commenting Policies