使用 try 语句如何避免竞争条件? [英] How does using the try statement avoid a race condition?

查看:41
本文介绍了使用 try 语句如何避免竞争条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

判断文件是否存在时,如何使用try语句避免竞争条件"?

When determining whether or not a file exists, how does using the try statement avoid a "race condition"?

我之所以这么问是因为一个高度赞成的答案(更新:它已被删除)似乎暗示使用 os.path.exists() 创造了一个否则不会存在的机会.

I'm asking because a highly upvoted answer (update: it was deleted) seems to imply that using os.path.exists() creates an opportunity that would not exist otherwise.

给出的例子是:

try:
   with open(filename): pass
except IOError:
   print 'Oh dear.'

但我不明白与以下情况相比如何避免竞争条件:

But I'm not understanding how that avoids a race condition compared to:

if not os.path.exists(filename):
    print 'Oh dear.'

如何调用 os.path.exists(filename) 允许攻击者对文件做一些他们还不能做的事情?

How does calling os.path.exists(filename) allow the attacker to do something with the file that they could not already do?

推荐答案

当然,竞争条件是在您的程序和其他一些对文件进行操作的代码之间(竞争条件总是需要至少两个并行进程或线程,请参阅this 了解详情).这意味着使用 open() 而不是 exists() 可能只在两种情况下真正有用:

The race condition is, of course, between your program and some other code that operates on file (race condition always requires at least two parallel processes or threads, see this for details). That means using open() instead of exists() may really help only in two situations:

  1. 您检查是否存在由某个后台进程创建或删除的文件(但是,如果您在 Web 服务器内部运行,这通常意味着您的进程的许多副本并行运行以处理 HTTP 请求,因此对于即使没有其他程序,也可能存在网络应用竞争条件).
  2. 可能有一些恶意程序正在运行,试图通过在您希望文件存在的时刻销毁文件来使您的代码崩溃.

exists() 只执行一次检查.如果文件存在,它可能会在 exists() 返回 True 后一微秒被删除.如果文件不存在,可以立即创建.

exists() just performs a single check. If file exists, it may be deleted a microsecond after exists() returned True. If file is absent, it may be created immediately.

然而,open() 不仅测试文件是否存在,而且还打开文件(并且原子地执行这两个操作,因此在检查和打开之间不会发生任何事情).通常文件在有人打开时无法删除.这意味着在 with 中,您可以完全确定:文件现在确实存在,因为它是打开的.虽然只在with里面是这样,而且在with块退出后,文件仍然可能被立即删除,把需要文件的代码放在with里面保证代码不会失败.

However, open() not just tests for file existence, but also opens the file (and does these two actions atomically, so nothing can happen between the check and the opening). Usually files can not be deleted while they are open by someone. That means that inside with you may be completely sure: file really exists now since it is open. Though it's true only inside with, and the file still may be deleted immediately after with block exits, putting code that needs file to exist inside with guarantees that code will not fail.

这篇关于使用 try 语句如何避免竞争条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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