Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Re: Writing to flock files in a daemon

by graq (Curate)
on Mar 07, 2002 at 16:11 UTC ( [id://150045]=note: print w/replies, xml ) Need Help??


in reply to Re: Writing to flock files in a daemon
in thread Writing to flock files in a daemon

Thanks for the hint so far. I have modified the code, as you suggested. Changed the open to truncate instead of append, and tried using select.

And yes, /tmp/_pid_file contains the PID.
This is fine until I run the script a second time, when /tmp/_pid_file gets truncated even though startup fails.

Any further suggestions?

# As before .. # ... sub main { my $start_mess = "===== Starting $TASK"; $start_mess .= " (@_)" if @_; $start_mess .= " ====="; error( $start_mess ); my $FH; open( HIGHLANDER, ">$PID_FILE") or die( "Cannot write to $PID_FILE +: $!" ); { my $count = 0; { flock HIGHLANDER, LOCK_EX | LOCK_NB and last; sleep 1; redo if ++$count < 3; error( "Script is already running." ); die( "Startup failed, PID file locked." ); } } $FH = select(HIGHLANDER); $| = 1; select($FH); print HIGHLANDER $$; # .. # ..as before..

<a href="http://www.graq.co.uk">Graq</a>

Replies are listed 'Best First'.
Re: Re: Re: Writing to flock files in a daemon
by bluto (Curate) on Mar 07, 2002 at 17:36 UTC
    Opening with ">" truncates the file. Since flock is and advisory lock (at least on Unix), it won't stop the second process from doing this. See open or "perldoc -f open".

    I tend to check for the file's existance first and then use "+<$file" if it's there and ">$file" if it's not. I think this is sloppy though since there is probably a race condition since the filecheck and the open occur at two different times (i.e. the file may come into existance between the file check and the open() call if another process was running at the same time). If the lock file is never really deleted after it is first, this probably isn't a problem.

    I'd suggest using sysopen with O_RDWR | O_CREAT and then truncating the file yourself just before you perform the write.

    bluto

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://150045]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (3)
As of 2024-04-26 02:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found