Go Back   Armenian Knowledge Base > Technical sections > Webmaster Zone > Web Development

Reply
 
Thread Tools

Locking a file
Old 23.02.2002, 17:38   #1
Moderator
 
acid's Avatar
 
Join Date: 09 2001
Location: South Korea, Gumi
Posts: 7,699
Blog Entries: 16
Rep Power: 7
Question Locking a file

How do I lock a certain file so other instances of my perl script inquire that it is locked and wait until it will be released. Is there any common way to do that. Example would be great.

Old 23.02.2002, 17:55   #2
VX
Консервативн
 
VX's Avatar
 
Join Date: 01 2002
Location: Кавказская Албания
Posts: 889
Rep Power: 0
Post

use Fcntl qw(:flock);#importiruem constatti dlya flock()-a

open(FH, ">/path/to/file")
or die "Can't open file: $!\n";
#otkrivaem dlya zapisi, vsya prejnyaya informaciya budet poterena

flock(FH, LOCK_EX); #DELAEM EXLUSIVE LOCK, ctob bol'she nikto ne trogalb@ etot file

..your staff here ..

(btw ne obyazatel'no otkrivat' dlya zapisi, mojno takje dlya cteniya , ctob sluchainno vo promejutok cteniya fila tam nicego ne izmenilos'bi)
close(FH); # pri vizove close, file avtpmatocheski razblokiruetsa, (mojno bilo takje zdelat' tak flock(FH, LOCK_UN);close(FH); )

.. that's it <img src="smooch-1.gif" border="0">

no k sojalenu blockirovka filov ne realizoavanna na vsex platformax v chasnist' na win9x, dos etc..


a teper' primer:
<blockquote><font size="1" face="MS Sans Serif, Verdana, Helvetica, sans-serif">code:</font><hr><pre>
#!/usr/bin/perl

#useradd pl, prostenk' script dlya dobavleniya #userov v unix, bez ispol'zovaniya tenevix paroley
#usage useradd.pl user cryptpass shell
#(c) VX

use Fcntl qw (:flock);
use strict;

my $uid = &getfreeid('u');
my $gid = &getfreeid('g');

open(PASSWD, ">>/etc/passwd") or die;
flock(PASSWD, LOCK_EX);
echo $ARGV[0].':'.$ARGV[1].":$uid:$gid:".$ARGV[2].":$homedir\n";

close(PASSWD);


sub getfreeid{

my ($mode) = @_;

open(PW,"/etc/passwd");
flock(PW, LOCK_EX);
my $id = undef;
my $f;
if ($mode eq 'g'){
$f = 3;
}elsif( $mode eq 'u')
$f = 2;
}
my $max = 0;
while(<PW&gt <img src="wink-5.gif" border="0"> {
my $id = (split(/:/,$_))[$f]
if ($max < $id){
$max = $id;
}
}
close (PW);
return $max+1;
}

</pre><hr></blockquote>
__________________
Праздник к нам приходит...

|^^^^^^^^^'''^\| ||\__
| ВОДКА-ВОДКА | ||','''|'''''''\_____,_
| _..... _ | ||_ _|'__|_____||.........| |
'(@)'(@)'(@)''''''''''''''''''''''*|(@)""""|(@)*
Reply




Реклама:
реклама
Buy text link .

All times are GMT. The time now is 20:04.
Top

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.