gpt4 book ai didi

ruby - 为什么当 File 对象是新对象时 flock() 的工作方式不同?

转载 作者:数据小太阳 更新时间:2023-10-29 08:56:45 25 4
gpt4 key购买 nike

这是代码,它可以工作:

f = File.new('test', File::CREAT | File::RDWR)
f.flock(File::LOCK_EX)
f.flock(File::LOCK_EX)
puts 'Works!'

但是,这个不起作用:

File.new('test', File::CREAT | File::RDWR).flock(File::LOCK_EX)
File.new('test', File::CREAT | File::RDWR).flock(File::LOCK_EX)
puts 'Works!'

你能解释一下这是为什么吗?我的实际问题是如何使第二个片段起作用?

最佳答案

how to make the second snippet work?

在尝试使用 LOCK_EX 重新锁定之前使用 LOCK_UN 解锁文件。或者不要使用 LOCK_EX

至于为什么会发生这种情况,请参阅 documentationflock(2) 上。

If a process uses open(2) (or similar) to obtain more than one file descriptor for the same file, these file descriptors are treated independently by flock(). An attempt to lock the file using one of these file descriptors may be denied by a lock that the calling process has already placed via another file descriptor.

关于ruby - 为什么当 File 对象是新对象时 flock() 的工作方式不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53011865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com