Skip site navigation (1)Skip section navigation (2)
Date:      Wed, 28 Jan 1998 08:39:04 -0800
From:      Don Wilde <don@partsnow.com>
To:        grobin@accessv.com, questions@FreeBSD.ORG
Subject:   Re: How Do You Lock File in UNIX?
Message-ID:  <34CF5F28.569EFFC4@partsnow.com>

next in thread | raw e-mail | index | archive | help
a simpler way is to create a file called .lock.filename, and delete it
when you leave. Your read and write routines will test for this file.

Here's some old Perl code (written prior to the P5 flock modules
becoming common) which shows the essence. I recommend the use of the
modules instead if you use P5.

-- 
  oooOOO O O O o * * *  *   *   *
 o     ___       _________ _________ ________ _________ _________ ___==_
 V_=_=_DW ===--- Don Wilde [don@PartsNow.com] [http://www.PartsNow.com ]
/oo0000oo-oo--oo-ooo---ooo-ooo---ooo-ooo--ooo-ooo---ooo-ooo---ooo-oo--oo


require "html.wilde";

package FILE;

sub append {
    local($file,@newtext) = @_;
    &lock($file);
    open(FILE,">>$file") || &HTML'error("FILE_APPEND: $file");
    print FILE join("\n",@newtext), "\n\n";
    &unlock($file);
}

sub backup {
    local($path,$file) = &dirbase($_[0]);
    chdir($path) || &HTML'error("FILE_BACK: CHDIR_$path"); #'
    &lock("$_[0]");
    unlink("$file.bak");
    link($file,"$file.bak") || &HTML'error("FILE_BAK: $file");
    &unlock("$_[0]");
}                               

sub lock {
    local($path,$file) = &dirbase($_[0]);
    chdir($path) || &HTML'error("2_$path:$_[0]");

    local($i) = 0;
    while ((-e ".lock.$file") && ( $i < 6 )) {
        sleep(1); $i++; if ($debugging) {print "locked board\n"}
    }
    (-e ".lock.$file") && (&HTML'error("3:.lock.$file"));
    open(LOCK,">.lock.$file") || &HTML'error("6: $path.lock.$file");
    close LOCK;
}                               

sub unlock {
    local($path,$file) = &dirbase($_[0]);
    chdir($path) || &HTML'error(2); #'
#chmod(0666,"$file") || print "Couldn't chmod $file\n";
    unlink(".lock.$file");
}


sub dirbase {
    $_[0] =~ m%^(/(([^/]*)/)*)([^/]*)%;
    local($path,$file) = ($1,$4);
    ($path,$file);
}


sub last_mod {
# returns 12/25/94 for a file last modified on Xmas, 1994
    local($mday,$mon,$year) = (localtime((stat("$_[0]"))[9]))[3..5];
    $mon++;
    return("$mon/$mday/$year");
}

sub created {
# returns 12/25/94 for a file created on Xmas, 1994
    local($mday,$mon,$year) = (localtime((stat("$_[0]"))[10]))[3..5];
    $mon++;
    return("$mon/$mday/$year");
}

1;



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?34CF5F28.569EFFC4>