1752795 Members
5956 Online
108789 Solutions
New Discussion юеВ

Re: Test for file open

 
SOLVED
Go to solution
Luis Toro
Regular Advisor

Test for file open

Is there a command to check (in a script) if a file is open? I am writing a script that checks a directory for files which are being either ftp'd from another server, or copied in remotely via samba. The script will move the files to another location for processing. The files can be rather large, so I'd like to put some check to make sure the file is not in the middle of being transferred. I'm thinking of checking new files twice and if the filesize is the same on both checks then its safe to assume the file is complete. Wondering if there is a better. Thought of a "done" file to indicate transfer completion, but that would entail some changes on the sending end.
Thanks
5 REPLIES 5
Bill Hassell
Honored Contributor
Solution

Re: Test for file open

The command is fuser as in:

fuser /etc/fstab

If the file is open (reading or writing), it will return the process ID(s) that are using it.


Bill Hassell, sysadmin
James R. Ferguson
Acclaimed Contributor

Re: Test for file open

Hi Luis:

You can test with 'fuser'. Here's a snippet of code I often use:

...

PIDS=`fuser ${FILE} 2> /dev/null` #...look for any processes...
if [ ! -z "${PIDS}" ]; then
print -u2 "Error: '${FILE}' is inuse by process(es): ${PIDS}"
fi

Regards!

...JRF...
Peter Nikitka
Honored Contributor

Re: Test for file open

Hi,

look for 'lsof' - it can report about open files:

http://gatekeep.cs.utah.edu/hppd/hpux/Sysadmin/lsof-4.77/

..., but I'm not shure, if your approach for 'locking' files is the right one.

mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"
Luis Toro
Regular Advisor

Re: Test for file open

Duh.
I don't know how often I've used the fuser command (when unmounting filesystems), and it didn't cross my mind that I could use it in this instance.

Thanks for the quick replies.
Patrick Wallek
Honored Contributor

Re: Test for file open

If you have lsof installed you can use it to see who is using a file.

The first example here shows what processes have a oracle data file open.

# lsof apd03.dbf
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
oraclepro 14739 oracle 34u VREG 64,0x2000a 524296192 6 apd03.dbf
ora_dbw0_ 16430 oracle 212uW VREG 64,0x2000a 524296192 6 apd03.dbf
ora_lgwr_ 16432 oracle 214u VREG 64,0x2000a 524296192 6 apd03.dbf
ora_smon_ 16436 oracle 208u VREG 64,0x2000a 524296192 6 apd03.dbf

If nothing has a file open then you will be returned to the prompt.

# lsof /etc/hosts

So something like this may work:

FILE=filename
OPEN=$(lsof ${FILE} | wc -l)
if (( ${OPEN} == 0 )) ; then
echo "${FILE} is not open"
else
echo "${FILE} is open"
fi