hello,lists,

I open a file and obtained a filehandle.then I fork a child and access this 
file in child (via the duplicate filehandle from parent).If both parent and 
child are writting to the file at the same time,the things should become 
terrible.So I should use the 'flock' call to lock the filehandle.But I find 
just in the same process,the flock is effective.In other words,when I flock the 
filehandle in child,the effect of 'flock' mean nothing to parent,and parent can 
still write to the file. the test code is shown as below:

use strict;
use warnings;
use Fcntl ':flock';

open (HDW,">>","tst.txt") or die "$!";
select HDW;$|=1;select STDOUT;

my $child = fork();
die "fork $!" unless defined $child;

if ($child == 0)
{
    flock (HDW,LOCK_EX);
    for (my $i=0;;$i++) {
        print HDW "test in child $$ $i\n";
        sleep 1;
    }
    flock (HDW,LOCK_UN);
    #close HDW;
    exit 0;
}

for (my $i=0;$i<50;$i++){
    print HDW "test in parent $$ $i\n" or die $!;
    sleep 1;
}
close HDW;

when this code run,both parent and child can write to the same file,and maybe 
at the same time.

How can I resolve this problem?thanks.


--
Jeff Pang
NetEase AntiSpam Team
http://corp.netease.com

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to