in reply to Finding if a file is open

flock could help you, although some editors use different tricks: they create a copy of the file with a specially mangled file name (for example vim uses sprintf ".%s.swp", $file) and check for its existence before opening a file.

Replies are listed 'Best First'.
Re^2: Finding if a file is open
by merrymonk (Hermit) on May 15, 2008 at 16:11 UTC
    Thank you for that suggestion.
    However, I am not sure if flock will help since I want to find
    out if the file is open by another applciation before I
    try an write to it by a Perl application.

      If the other application (OA) is using file locking then flock() is the correct way. You first open() the filehandle. (There is no harm in this even if the OA is using the file.) Then you call flock() to attempt to acquire the write permission to the file. The return status tells you whether the file has been locked ('in use') by an OA.

      If the other application is using some proprietary locking scheme then of course you have to deduce what that scheme is.


      s//----->\t/;$~="JAPH";s//\r<$~~/;{s|~$~-|-~$~|||s |-$~~|$~~-|||s,<$~~,<~$~,,s,~$~>,$~~>,, $|=1,select$,,$,,$,,1e-1;print;redo}

      flock will help. Just do:

      use Fcntl; # get LOCK_EX constant open F, $file or error("Can't open $file $!\n"); flock(F, LOCK_EX) or error ("Can't get exclusive lock, file open and l +ocked by other app $!\n"); close F;

      Alternatively there is a program called oh.exe in the windows resource kit that returns a list of open file handles and the programs that have them open. handle.exe which came from sysinternals (now M$) can do the job on a specific file. If you look hard enough you may be able to find the underlying code and convert this perl.