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

Hi Monks,

I have a script that is run every minute on a machine to automate some processes and communicate with a server. However if 2 of the scripts are running at the same time, it does not end well. To get around this I used "flock or die" on a file I create at the root of C:. This has worked perfectly on every single windows OS I have tried, apart from Vista.

For some reason, even if the process is the first to run since the machine has booted up, Vista very rarely grants the lock to the process the script is running in, thus the script exits and this will then repeat itself every minute.

I have also tried simply checking for the existing of the lock file, but this doesnt work either as somehow vista manages to create the file before checking if it exists, despite the check coming first in the code.

Do you know of any alternatives to flock that I can use in order to stop more then one script running at any given time?

Thanks In Advance!

Replies are listed 'Best First'.
Re: Frustration with File Locking in Vista
by cdarke (Prior) on Dec 02, 2008 at 12:32 UTC
    You might be better using a Mutex instead of a lock file. The following code has not been tested on Vista (I don't have the courage to try):
    use strict; use warnings; use Win32::Mutex; # This returns a handle to the mutex, and optionally creates it my $mutex = Win32::Mutex->new(0, 'appln_mutex_name'); # Grab the lock, or block $mutex->wait; # This is for testing purposes # Insert some clever Perl stuff here print "Hit <RETURN> to continue"; <STDIN>; # release the lock $mutex->release;
Re: Frustration with File Locking in Vista
by Corion (Patriarch) on Dec 02, 2008 at 12:09 UTC

    As Windows supports mandatory file locking, you can simply open the file for writing and do that with the FILE_FLAG_DELETE_ON_CLOSE flag, so when your process goes away so will the file. See Win32API::File for the nitty-gritty. Alternatively, you can try the same with a pipe/mailbox in //./PIPE/$0 and thus circumvent the need for a physical file.

    Of course, when creating the file fails, you can assume that another instance of your process is already running.

Re: Frustration with File Locking in Vista
by gwadej (Chaplain) on Dec 02, 2008 at 14:09 UTC

    Unlike previous versions of Windows, Vista does not leave the root directory writable by everyone by default.

    G. Wade
Re: Frustration with File Locking in Vista
by Anonymous Monk on Dec 02, 2008 at 15:46 UTC
    Thanks to all who replied! I managed to get it working :)

    cdarke, you'll be happy to know your Mutex solution worked perfectly on Vista :)
Re: Frustration with File Locking in Vista
by Bloodnok (Vicar) on Dec 02, 2008 at 12:25 UTC