# subroutine name: writedata # Writes in all the data from passed array of lines to $datafile. # Input: filename, reference to array of file lines # Owerwrites file, if already exists # If error occurs, makes CGI process exit with error # Returns: nothing # # Global variables used: # $no_flock - disable flock or not sub writedata { my($datafile,$r_rows) = @_; # If OS (like Win95) desn't support flock, we have to # go unreliable and slow way and create "lock" file GetFileLock("$datafile.lock"); my $existed = -e $datafile; use Fcntl qw( O_RDWR O_WRONLY O_CREAT O_TRUNC ); local *DATA; if (sysopen(DATA, $datafile, &O_WRONLY | &O_CREAT)) { # Exclusive locking flock(DATA, 2) unless ($no_flock); truncate(DATA, 0) or die "Can't truncate $datafile. Reason: $!"; foreach my $line (@$r_rows) { print DATA $line; } # unlock file flock(DATA, 8) unless ($no_flock); close(DATA); chmod(0666, $datafile) unless ($existed); ReleaseFileLock("$datafile.lock"); } else { ReleaseFileLock("$datafile.lock"); die("Error in subroutine writedata: Can't open $datafile. Reason: $!"); } }