Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Finding out if a file is opened by another process

Status
Not open for further replies.

Wonboodoo

MIS
Nov 13, 2002
187
US
How in Perl can you tell if a file is opened by another process? i.e. I'm looking for something similar to the unix "fuser" command.

I tried working with "flock" but it only works if the other process has explicitly acquired a lock on the file. If the other process has not then "flock" fails to detect it.

My preference is to not make a system call to "fuser" from Perl.

Thanks,
David
 
David,

lsof, if it's available to you, might be a better choice than fuser. I'm not aware of any pure Perl way to tell if a file is open or not.

Mike

"Deliver me from the bane of civilised life; teddy bear envy."

Want to get great answers to your Tek-Tips questions? Have a look at faq219-2884

 
I found this as an answer to someone elses question, haven't tested it, but it looks along the right lines:

Code:
$param = $ARGV[0];
if (-f "/lockdir/$param") {
  echo "already running\n";
  exit;
}

Rob Waite
 
Rob hi,

I think you'll find that the -f operator just checks for the existence of a plain file.

Mike

"Deliver me from the bane of civilised life; teddy bear envy."

Want to get great answers to your Tek-Tips questions? Have a look at faq219-2884

 
I found an answer on usenet (google groups). I don't have the link right now, but it involves using the "stat" command on the file and comparing the "dev" and "ino" entries with all those that can be found in /proc/*/fd/* (which contain file descriptors of all running processes).

If any of the /proc/*/fd/* have the same "dev" and "ino" (as returned by "stat") as the file you're interested in then a process has the file open.

There are caveats to this method:
1) Your operating system must use this /proc/*/fd/* system. Solaris does, I think Linux might too, but I'm pretty sure a lot of others do not.
2) Unless the Perl script is running as "root" it will only be able to look at /proc/*/fd/* files for processes running under the same userid. So you must run the Perl script as root or be sure that the only other process(es) that could have the file open are those that are running under the same userid as the Perl script is running under (which is true in my case).

Thanks for your input.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top