当您再次使用open时,文件锁定会保留吗? [英] Do file locks stay when you use open for a second time?

查看:136
本文介绍了当您再次使用open时,文件锁定会保留吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设:

  my $ fh; 
打开$ fh,>>,file.txt;
flock($ fh,LOCK_EX);
打开$ fh,+<,file.txt;
close $ fh;

文件锁定会保留还是会被释放?如果它将被释放有办法让它留下来?
云找不到相关信息。

解决方案

调用打开在已经分配给一个打开的文件描述符的文件句柄上执行文件句柄的隐式关闭。并关闭一个锁定的文件句柄释放锁。



在两个不同的模式下打开同一个文件句柄,不知道你在做什么。如果你使用第二个文件句柄,那怎么办?

 打开我的$ fh,>>,file.txt; 
flock($ fh,LOCK_EX);
打开我的$ fh2,+<,file.txt;
...用$ fh2 ...
重写'file.txt'关闭$ fh2; #重写
close $ fh; #使用锁






它看起来像<$对于 +< 模式中的文件(在Linux中工作,这可能不可移植),c $ c> flock 和一些 seek 语句,你只需要一个文件句柄。

 #在使用'+<'模式之前,请确保文件已经存在
{open my $ touch,'>>','file.txt'; }

打开我的$ fh,'+<','file.txt';
flock $ fh,LOCK_EX;

seek $ fh,0,2;
打印$ fh'文件结尾的内容';

seek $ fh,0,0;
打印$ fh'文件开始的东西';

close $ fh; #释放锁


Suppose:

my $fh;
open $fh, ">>", "file.txt";
flock($fh, LOCK_EX);
open $fh, "+<", "file.txt";
close $fh;

Will the file lock stay or will it be released? If it will be released is there a way to make it stay ? I cloud not find relevant information.

解决方案

Calling open on a filehandle that is already assigned to an open file descriptor performs an implicit close on the filehandle. And closing a locked filehandle releases the lock.

It's not clear to me what you are trying to do by opening the same file with the same filehandle in two different modes. What if you used a second filehandle?

open my $fh, ">>", "file.txt";
flock($fh, LOCK_EX);
open my $fh2, "+<", "file.txt";
... rewrite 'file.txt' with $fh2 ...
close $fh2;   # done with rewrite
close $fh;    # done with lock


It looks like flock is respected for a file in +< mode (works in Linux, this might not be portable), so with that and some seek statements, you only need a single filehandle.

# make sure file exists before you use '+<' mode
{ open my $touch,'>>','file.txt'; }

open my $fh, '+<', 'file.txt';
flock $fh, LOCK_EX;

seek $fh, 0, 2;
print $fh 'stuff for the end of the file';

seek $fh, 0, 0;
print $fh 'something for the start of the file';

close $fh;  # releases lock

这篇关于当您再次使用open时,文件锁定会保留吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆