I am looking for a perl code that reads/writes to a data file, every time any other program tries to read/write from that file the reading/writing program will block until the first will complete
To make things simpler I am currently trying to have a program which reads a file , sort the file and pop the first line.
For e.g , input file is: (called "a_file")
8 7 6 5 4 3 2 1
If 3 processes are running in parallel or serially, the final file will be:
1 2 3 4 5
I wrote:
#! /usr/local/bin/perl chomp($pid = $$); $LOCK_EXCLUSIVE = 2; $UNLOCK = 8; $fifo = "ENV{HOME}/a_file"; popup($fifo); sub popup { my($fifo) = @_; while (! -e "$fifo.lock") { open (LOCK, "> $fifo.lock") || die "problem opening $f +ifo\n"; flock LOCK , $LOCK_EXCLUSIVE; print LOCK $pid; open (FILE, "< $fifo") || die "problem opening $fifo\n +"; @lines = <FILE>; close(FILE) || warn "update queue file exited $?\n";; open (FILE, "> $fifo") || die "problem opening $fifo\n +"; @sorted = sort @lines; $pop = shift @sorted; print "$hostname is poping $pop\n"; print FILE "@sorted\n"; close(FILE) || warn "update queue file exited $?\n";; close(LOCK) || warn "lock file exited $?\n";; $str=`cat $fifo.lock`; flock LOCK, $UNLOCK; } if ($pid eq $str) { print "PID lock file is going to be removed\n" ; system("rm $fifo.lock"); } }
But it looks that while I running in parallel on 3 different hosts it does not work as I expect , I get:
linux24 is poping PID lock file is going to be removed linux28 is poping PID lock file is going to be removed
Also I found this code over the web but I fail to run it , it get into infinite loop –
chdir; # go home $FIFO = '.signature'; $ENV{PATH} .= ":/etc:/usr/games"; while (1) { unless (-p $FIFO) { unlink $FIFO; system('mknod', $FIFO, 'p') && die "can't mknod $FIFO: $!"; } # next line blocks until there's a reader open (FIFO, "> $FIFO") || die "can't write $FIFO: $!"; print FIFO "John Smith (smith\@host.org\n"; close FIFO; sleep 2; # to avoid dup signals }
Any idea? I will highly appreciate if you can advise.
Janitored by Corion: Added formatting, code tags, as per Writeup Formatting Tips
GrandFather added readmore tags
In reply to mkfifo/mknode by azaria
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |