Wednesday, August 06, 2008

The fuser Command

fuser is one of the *nix commands that I have started seeing myself use more and more frequently. It is a very powerful command, yet often forgotten. So what is it? fuser displays the process IDs of the processes that are using the files specified.

Identifying Processes
The following example shows how you can use the fuser command to find out which process is writing a log file called log.txt. fuser tells you the process ID (24976), which you can then use in a ps command to find out what the process is. In this case, its java.

sharfah@starship:~> ls -ltr
-rw-rw-r--   1 sharfah   sharfah     2836 Aug  6 00:08 log.txt

sharfah@starship:~> fuser -u log.txt
log.txt:    24976o(sharfah)

sharfah@starship:~> ps -ef | grep 24976
  sharfah 24976 24963  0 23:49:00 ?       13:39 java -server
  sharfah  6284 17191  0 00:09:54 pts/1    0:00 grep 24976
Used in this way, fuser can help tell you which process is responsible for creating large log files on your filesystem!

Killing Processes
The -k flag, sends the SIGKILL signal to each process using the file. This is handy if you want to "kill -9" a process without hunting for its PID first. Alternatively, if you want to send another signal type, use the -s flag. e.g. to send SIGTERM use -s TERM. The -k option is equivalent to -s KILL or -s 9. Most of my shutdown scripts, simply call fuser -s TERM on the process's log file.

Because fuser works with a snapshot of the system image, it may miss processes that begin using a file while fuser is running. Also, processes reported as using a file may have stopped using it while fuser was running. These factors should discourage the use of the -k option.

1 comment:

  1. Anonymous4:34 AM

    i cannot get any process id from a text file which my script creates . Iam echo'ing some value to my text file .

    ReplyDelete

Note: Only a member of this blog may post a comment.