当您再次使用open时,文件锁定会保留吗?

编程入门 行业动态 更新时间:2024-10-11 19:25:22
本文介绍了当您再次使用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时,文件锁定会保留吗?

本文发布于:2023-11-13 04:46:03,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:当您   文件   open

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!