windows CreateFile 如何通过 FILE_SHARE_READ 失败并通过 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE 成功?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5339882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:27:30  来源:igfitidea点击:

How can CreateFile fail with FILE_SHARE_READ and succeed with FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE?

windowswinapifile-ioprocess

提问by Benoit

Try it yourself:

自己试试:

Create an XLS file, open it in Excel.

创建一个 XLS 文件,在 Excel 中打开它。

Open sysinternals Process Monitor, and watch what happens while you make a copy of your XLS file in the explorer (just hit ctrl-c ctrl-v).

打开 sysinternals Process Monitor,观察在资源管理器中复制 XLS 文件时会发生什么(只需按 ctrl-c ctrl-v)。

Two calls to ::CreateProcessin a row. First call asks for read permissions, and gets Access denied. Second call asks for read plus write plus delete and passes.

::CreateProcess连续两次调用。第一次调用请求读取权限,并拒绝访问。第二个调用要求读加写加删除并通过。

Is that normal?

这是正常的吗?

回答by Erik

If you open a file with FILE_SHARE_READyou're saying you're willing to share access to this file, but only for reads.

如果您打开一个文件,则FILE_SHARE_READ表示您愿意共享对该文件的访问权限,但仅限于读取。

If you open with all the flags, you're willing to share access also for writes/delete.

如果您打开所有标志,您也愿意共享写入/删除的访问权限。

FILE_SHARE_READis more restrictive than FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE

FILE_SHARE_READFILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE

If some other process (excel) has this file opened for e.g. write (and it has the sharing flags set), the only way you can access it is to accept sharing it for write.

如果某个其他进程 (excel) 为例如写入打开了此文件(并且设置了共享标志),则您可以访问它的唯一方法是接受共享以进行写入。

回答by Luke

You have to use compatible sharing modes. If Excel opens the file with FILE_SHARE_READ | FILE_SHARE_WRITE then subsequent attempts to open the file must use at least those same flags. Specifically from the MSDN documentation on CreateFile:

您必须使用兼容的共享模式。如果 Excel 使用 FILE_SHARE_READ 打开文件 | FILE_SHARE_WRITE 然后随后尝试打开文件必须至少使用那些相同的标志。具体来自CreateFile 上MSDN 文档

You cannot request a sharing mode that conflicts with the access mode that is specified in an existing request that has an open handle. CreateFile would fail and the GetLastError function would return ERROR_SHARING_VIOLATION.

您不能请求与具有打开句柄的现有请求中指定的访问模式冲突的共享模式。CreateFile 将失败并且 GetLastError 函数将返回 ERROR_SHARING_VIOLATION。