danstuken has asked for the wisdom of the Perl Monks concerning the following question:
I fear this may well be a FAQ or the combination of a couple of them. Forgive me if this is the case.
All I want is to lock a file. Truthfully. Its got so bad that this is the limit of my ambition. In the main I'm not a perl numpty, but this is driving my looney.
Running on an FC4 box I have the following code to reset (i.e. remove) an entry from the current user's ssh known_hosts file. I cannot get the lock to work. I have commented some of the artifacts of what I've already tried. Please guide me to enlightenment.
Many thanks for any help.#!/usr/bin/perl my $host = $ARGV[0]; my $known_hosts = './kh.tt'; ##USE '>>' OTHERWISE WE WILL TRUNCATE AT open() - BEFORE WE HAVE THE L +OCK!! #do{ # print 'Error opening ssh known hosts file : ', $!, "\n"; # exit; #}unless( open KNOWN_HOSTS, ">> $known_hosts" ); open LOCK, "> $known_hosts.sem" or die "Can't open semaphore: $!\n"; ##lock the file my $lock_tries = 3; my $got_lock = 0; GETLOCK: while( $lock_tries ) { print "TRYING FOR LOCK ($lock_tries)\n"; #if( flock(KNOWN_HOSTS, LOCK_EX|LOCK_NB) ) my $ret = flock(LOCK, LOCK_EX|LOCK_NB); print "Flock ret : $ret\n"; if( $ret ) { print "GOT LOCK\n"; $got_lock = 1; last GETLOCK; } sleep(1); $lock_tries --; } do{ print 'Unable to lock known hosts file for updates', "\n"; close LOCK; exit; } unless($got_lock == 1); #open KNOWN_HOSTS_RD, "< $known_hosts"; open KNOWN_HOSTS, "+< $known_hosts" or die "Can't open data file: $!\n +"; #my @host_data = <KNOWN_HOSTS_RD>; my @host_data = <KNOWN_HOSTS>; #close KNOWN_HOSTS_RD; my $host_pattern = $host; $host_pattern =~ s/\./\\\./; my @new_data = grep(!/^$host_pattern/,@host_data); truncate KNOWN_HOSTS, 0; print KNOWN_HOSTS join("\n", @new_data); ##This releases the lock. close(KNOWN_HOSTS); close LOCK;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: flock(), dodgy return?
by radiantmatrix (Parson) on Aug 01, 2007 at 13:46 UTC | |
by danstuken (Novice) on Aug 01, 2007 at 14:03 UTC | |
by ikegami (Patriarch) on Aug 01, 2007 at 14:09 UTC | |
by danstuken (Novice) on Aug 01, 2007 at 14:39 UTC | |
by danstuken (Novice) on Aug 01, 2007 at 14:19 UTC | |
|
Re: flock(), dodgy return?
by oxone (Friar) on Aug 01, 2007 at 14:21 UTC | |
by ikegami (Patriarch) on Aug 01, 2007 at 14:31 UTC | |
by danstuken (Novice) on Aug 01, 2007 at 14:38 UTC | |
by danstuken (Novice) on Aug 01, 2007 at 14:35 UTC | |
|
Re: flock(), dodgy return?
by Corion (Patriarch) on Aug 01, 2007 at 14:28 UTC | |
|
Re: flock(), dodgy return?
by moritz (Cardinal) on Aug 01, 2007 at 13:59 UTC | |
by danstuken (Novice) on Aug 01, 2007 at 14:20 UTC |