在并发环境中追加到文件末尾
如果同时运行以下多个(示例)程序,需要采取哪些步骤来确保“完整”行始终正确附加到文件末尾。
#!/usr/bin/env python
import random
passwd_text=open("passwd.txt","a+")
u=("jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/sh",
"jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/sh",
"xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/sh")
for i in range(random.randint(1,2)):
print >> passwd_text, random.choice(u)
passwd_text.close()
并且:即使磁盘已满,或者已设置“ulimit -f”,是否可以保证“全有或全无”追加(在 linux/unix 上)?
(注意类似的问题:如何附加到文件?)
What steps need to be taken to ensure that "full" lines are always correctly appended to the end of a file if multiple of the following (example) program are running concurrently.
#!/usr/bin/env python
import random
passwd_text=open("passwd.txt","a+")
u=("jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/sh",
"jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/sh",
"xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/sh")
for i in range(random.randint(1,2)):
print >> passwd_text, random.choice(u)
passwd_text.close()
And: Can an "all or nothing" append be guaranteed (on linux/unix) even if the the disk becomes full, or "ulimit -f" has been set?
(Note similar question: How do you append to a file?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为在 python 的正常
open
函数中对 这个“bug” 的讨论表明你没有得到 POSIX 原子保证,但是如果你使用http://docs.python.org/2/library/io.html#io.open
如果操作系统正确实现其 write sys 调用.. .
http://bugs.python.org/issue15723
I think the discussion of this "bug" in python's normal
open
function suggests that you don't get the POSIX atomic guarantee, but you do if you usehttp://docs.python.org/2/library/io.html#io.open
if the operating system implements its write sys call correctly...
http://bugs.python.org/issue15723
您必须锁定该文件以确保没有其他人同时写入该文件。请参阅文件锁定和lockfile 或 posixfile 了解更多细节。
更新:如果磁盘已满,则无法将更多数据写入文件。我不确定Python的输出重定向的实现,但是
write
系统调用可以写入比请求更少的字节。You have to lock the file in order to ensure that nobody else is writing to it at the same time. See File Locking and lockfile or posixfile for more details.
UPDATE: And you cannot write more data into the file if the disk is full. I am not sure about Python's implementation of output re-direction, but
write
system call can write less bytes than requested.