Question Unix - How To Check If File Is In Use?

rzr

Member
Progress 10.2B / CHUI / UNIX.

How do I check in UNIX if a file is already open and it's content being read by another program? Is this possible in UNIX.

At the moment I'm thinking of creating a temp log file ( or a temp db record ) when this program executes, so if any other process were to trigger this program it will first check if the temp log exists. If the log does not exists the continue with program execution....
 

TheMadDBA

Active Member
lsof is your friend...

lsof yourfilename

then check the return code.

Lock files with the process id of the parent process is also a good idea though.
 

Rob Fitzpatrick

ProgressTalk.com Sponsor
It sounds like you don't have to use the file system to build this interlock. You could have the program try to lock a control record in a table when it starts. If it can then no other instance of the program is running. Downgrade it to a share lock so you don't have a transaction scoped to the procedure.

If another instance of the program runs, it won't be able to get the exclusive lock, because the first instance still has it share-locked, which you can detect and take whatever action is necessary.

And if the first instance dies, its locks get cleaned up automatically so the next instance of the program will run successfully. Whereas control files (like "flag.PID" or whatever) have to be cleaned up manually after a crash.
 

rzr

Member
lsof gave below error. I ran command lsof /home/myuserid

lsof: can't open /dev/mem: No such file or directory
lsof: can't open /dev/kmem: No such file or directory

at this moment we are taking the control file route but I do like the approach of doing this lock using a db record. Will try this too.
 

Cecil

19+ years progress programming and still learning.
With lsof you need to be root to see details of other users' handles.

Just chucking in my two cents. I too was having a problem with Samba/SMB locking PDF files by users opening files with Adobe Acrobat Reader and needed to make sure that they [PDF] were not locked.

I use the sudo command to run the lsof command. Now to stop sudo prompting for a password each time it's executed, I added the following line to my /etc/sudoers file: "progress ALL=(root) NOPASSWD: /usr/sbin/lsof" (without quotes). 'progress' is just the username that I use for all my broker/agents sessions.

So the OS-Command is something like this:
Code:
sudo lsof bae7a8fb-0b1d-30aa-e211-4cb11e4f9b83.pdf;echo $?
 
Top