是否有 Windows 等价于 `openat`? [英] Is there a Windows equivalent of `openat`?

查看:19
本文介绍了是否有 Windows 等价于 `openat`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题几乎说明了这一点,在 Windows 上,我可以使用类似于 openat 的东西以某种方式模拟多线程应用程序中的多个工作目录吗?

The title pretty much says it, on Windows, can I somehow simulate multiple working directories in a multithreaded application by using something similar to openat?

另见这个问题.

推荐答案

是的,它叫做 NtCreateFile() (https://msdn.microsoft.com/en-us/library/bb432380(v=vs.85).aspx):)

Yes there is, and it's called NtCreateFile() (https://msdn.microsoft.com/en-us/library/bb432380(v=vs.85).aspx) :)

openat() 将打开的 fd 带到路径操作开始的基本目录.类似地,您可以为 NtCreateFile() 的 ObjectAttributes.RootDirectory 提供一个 HANDLE,以将该目录的任何路径用作相对路径操作的基础.

openat() takes an open fd to a base directory from which path operations start. Similarly, you can supply a HANDLE to the ObjectAttributes.RootDirectory of NtCreateFile() to have whatever that directory's path is to be used as a base for relative path operations.

如果直接使用 NT 内核 API 对您来说太过分了,并且您想保留在 Win32 中,您可以很容易地检索基目录 HANDLE 的当前路径(请参阅 https://msdn.microsoft.com/en-us/library/windows/desktop/aa366789(v=vs.85).aspx).如果您在没有 FILE_SHARE_DELETE 权限的情况下打开目录,则没有人能够重命名它,因此只要您保持 HANDLE 打开,检索到的路径就永远不会移动.

If going direct to the NT kernel API is too much for you and you want to remain within Win32, you can retrieve the current path of the base directory HANDLE easily enough (see https://msdn.microsoft.com/en-us/library/windows/desktop/aa366789(v=vs.85).aspx). If you open the directory without FILE_SHARE_DELETE permissions, nobody will be able to rename it and therefore the path retrieved will never move so long as you keep the HANDLE open.

然后使用普通字符串连接将检索到的路径与相对路径拼接在一起.

You then stitch together the retrieved path with the relative path using normal string concatenation.

NT 内核 API 方法是 Windows 上唯一允许基目录 HANDLE 由第三方进程任意重命名并且不会导致代码竞争的解决方案.即它是 POSIX openat() 的唯一等价物.我同意非常不幸的是,Win32 没有提供此功能 - 事实上,Win32 没有提供原子重命名,这是一个非常有用的 POSIX 功能,确实可以让您避免锁定文件,并且 NT 内核 API 也提供了这些功能.

The NT kernel API approach is the only solution on Windows which allows the base directory HANDLE to be arbitrarily renamed by third party processes and that not cause races in your code. i.e. it's the only equivalent to POSIX openat(). I agree it's very unfortunate that Win32 doesn't make available this facility - in fact, Win32 doesn't make available atomic renames which is a very useful POSIX facility indeed to let you avoid lock files and is something the NT kernel API provides too.

这篇关于是否有 Windows 等价于 `openat`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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