jonnyfolk has asked for the wisdom of the Perl Monks concerning the following question:

I have a file which currently is editable from two different scripts. It is not clear to me (after reading perldocs) whether I can effectively lock the file by applying flock to calls in both scripts, or whether I should endeavour to make one script a subroutine of the other, to allow flock to function.

Perhaps there is a particular way this might be approached? I would be grateful for any enlightenment.

Replies are listed 'Best First'.
Re: flock for same file different scripts
by grantm (Parson) on Apr 20, 2003 at 20:17 UTC

    Yes, using flock will allow you to safely edit the same file from two different scripts (or two different instances of the same script, or even one script and one C program).

      Thanks, grantm - that's eased my concern...

      Just for the record I have the impression that flock works on the filehandle rather than the file - is it the case that filehandles in all scripts should use the same name in order to flock properly, or is it the path/filename which holds sway?

      It's not a problem as I have used the same filehandle anyway, but just to get to the bottom of this...

        No, it's definitely the pathname that you're locking. The name you chose for the filehandle when you opened the file is not relevant to the locking process.

Re: flock for same file different scripts
by perlplexer (Hermit) on Apr 20, 2003 at 20:58 UTC
    flock() is Perl's shortcut to lockf(), which is in turn a shortcut to fcntl()'s locking capabilities.
    File locks are maintained by the OS, not by the program. The program simply requests a lock from the OS by making a call to flock(). So, as grantm pointed out already, you're safe as long as all programs play by these rules and use flock(), or lockf(), or fcntl(), or whatever the equivalent may be.

    --perlplexer