简体   繁体   English

文件锁定似乎不起作用(flock / lockf)

[英]File locking seems not to work (flock/lockf)

In my project we have some scripts that start the application, do some performance tests and then kill the application. 在我的项目中,我们有一些脚本可以启动应用程序,进行一些性能测试,然后终止该应用程序。 The problem is that sometimes something bad happens to the script, like a crash. 问题是脚本有时会发生一些坏事,例如崩溃。 Then our application hangs "in the air". 然后我们的应用程序“挂在空中”。

I wanted to fix that by writing pid value to file that contains pid/pids of the application, but to do it properly (I think) I wanted to do something like this: 我想通过将pid值写入包含应用程序的pid / pids的文件来解决此问题,但是要正确地做到这一点(我认为),我想这样做:

lock the file
process the pid/pids
clean file entries
unlock the file

I then searched how to lock the files in Python 2.7 (because we are using it for writing our scripts), so I found out about https://docs.python.org/2/library/fcntl.html and flock and lockf methods, but I am doing something wrong I think. 然后,我搜索了如何在Python 2.7锁定文件(因为我们正在使用它来编写脚本),因此我找到了https://docs.python.org/2/library/fcntl.html以及flocklockf方法,但我认为做错了。

I wanted to test if those methods work properly so I did: 我想测试一下这些方法是否正常工作,所以做到了:

echo "test" > testFile
(open repl)
>>> import fcntl
>>> f = open("testFile", "rw")
>>> fcntl.flock(f, fcntl.LOCK_EX)

and even if I locked the file (or at least I think I did) I could do 即使我锁定了文件(或者至少我认为是的),我也可以做到

echo "aaa" >> testFile

in other terminal session and it succeeded, the file was changed, no errors. 在其他终端会话中,它成功完成,文件已更改,没有错误。

If there is a os specific trick I should use (but I doubt that python standard library can't handle locking in portable way) this needs to work on Linux. 如果有特定于操作系统的技巧,我应该使用(但我怀疑python标准库不能以可移植的方式处理锁定),这需要在Linux上运行。

By default file locks are advisory, meaning they only work when all processes cooperate ie they check to see if the file is locked before attempting I/O. 默认情况下,文件锁是建议性的,这意味着它们仅在所有进程配合时才起作用,即它们在尝试I / O之前检查文件是否被锁定。 There is nothing stopping a process from ignoring an advisory lock and just writing to the file. 没有什么能阻止进程忽略咨询锁并仅写入文件。

There are also mandatory locks through which the system coerces other processes to respect the locks. 还有强制性锁,系统通过这些强制性强制其他进程遵守这些锁。 This is probably what you want and should google "mandatory locks linux" for the details, which mostly involve mounting the file systems in question with some parameters. 这可能是您想要的,应该使用谷歌“强制性锁定linux”获取详细信息,该过程主要涉及使用某些参数挂载有问题的文件系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM