views:

284

answers:

7

In Perl, how do I test if a file of open by another Perl program? I need the first program to be done before the second program can start.

+4  A: 

You may be able to coordinate the two programs using flock: The first program would lock the file, and the second program would also try to acquire a lock on it, and it would block until the first program releases the lock.

Nathan Kitchen
This is the Right Solution.
MarkR
A: 

To specifically look for whether or not a file is open or in use, if you're on unix there is a wrapper to the lsof command to list open files: Unix::Lsof

jsoverson
Doing so would be inefficient, and in any case is guaranteed to cause a race condition.
MarkR
+5  A: 

Is flock() available on your system ? Otherwise, the two programs have be be synchronized, they can communicate thru a pipe or a socket, or via the presence/absence of a file.

Another direction if you are on a Unix-like system, could be use lsof output.

I assume having the first program starting the second one is not feasible.

philippe
+4  A: 

In my experience, flock works fine on local systems on both Windows and Linux.

You could also, presumably, have the first program exec the second program when it's done processing the file.

Sinan Ünür
+10  A: 
friedo
Nice post, and it got you the silver perl badge. Congratulations!
Ether
+3  A: 

If you are running on Windows, you could call CreateFile directly with a dwShareMode of 0.

According to MSDN:

Prevents other processes from opening a file or device if they request delete, read, or write access.

There may be a Perl module that handles this, otherwise you could use Win32::API, to call the function.

Brad Gilbert
A: 

If you're in Unix, you could also call fuser.

Anon Guy