Friday, February 27, 2009

Checking for open files

A coworker presented me with an interesting problem today. We have an SFTP server set up, where a client is uploading a series of files on a pretty regular basis. My coworker needed to process the files as soon as they were finished uploading, but he didn't know how to tell when it was finished. Since the SFTP server would be keeping the file open until it was finished writing it, all we needed to do was find out whether the file was still open.

In Bash, there's an easy way to check for this. When called without any arguments, the lsof program shows a list of all open files on the system. You can also call it with the full path of the filename that you are checking, and it will show only the processes that have that file open. For example, we can look at /dev/null, which seems to pretty much always be open on my system:

$ lsof /dev/null
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
gconfd-2 6668 jhall 0u CHR 1,3 6663 /dev/null
gconfd-2 6668 jhall 1u CHR 1,3 6663 /dev/null
gconfd-2 6668 jhall 2u CHR 1,3 6663 /dev/null
...snip...

The lsof program also has an exit status of 0 if it returns any information, and an exit status of 1 if it did not. Since we're only interested in that error status and not in any of the information returned, we can throw it away by redirecting STDOUT and STDERR to /dev/null with &>:

$ lsof /dev/null &> /dev/null && echo "The file is open" || echo "The file is not open"
The file is open

Breaking this down a little further, if "lsof /dev/null &> /dev/null" was successful (returned an error status of 0), then it will run the first echo command. If not, that will make both the lsof command and the first echo command unsuccessful (error status of 1 for both) and the echo command after the pipes will run.

If it's a little confusing having "/dev/null" in that command twice, try running it on a file that's likely to not be open, like /proc/cpuinfo:

$ lsof /proc/cpuinfo &> /dev/null && echo "The file is open" || echo "The file is not open"
The file is not open

Just a handy little bit of Bash Fu to brighten your day.

No comments:

Post a Comment

Comments for posts over 14 days are moderated

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