如何使 Windows 文件锁定更像 UNIX 文件锁定? [英] How do I make Windows file-locking more like UNIX file-locking?

查看:29
本文介绍了如何使 Windows 文件锁定更像 UNIX 文件锁定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

UNIX 文件锁定非常简单:操作系统假定您知道自己在做什么,并让您做自己想做的事:

UNIX file-locking is dead-easy: The operating system assumes that you know what you are doing and lets you do what you want:

例如,如果您尝试删除另一个进程打开的文件,操作系统通常会让您这样做.原始进程仍然保留它的文件句柄,直到它终止——此时文件系统将悄悄地回收磁盘资源.不客气,这就是我喜欢的方式.

For example, if you try to delete a file which another process has opened the operating system will usually let you do it. The original process still keeps it's file-handles until it terminates - at which point the the file-system will quietly re-cycle the disk-resources. No fuss, that's the way I like it.

Windows 上有什么不同:如果我尝试删除另一个进程正在使用的文件,我会收到操作系统错误.在原始进程释放它对文件的锁定之前,该文件是不可访问的.这在 MS-DOS 的单用户时代非常棒,当时任何锁定过程都可能在包含文件的同一台计算机上,但在网络上这是一场噩梦:

How different things are on Windows: If I try to delete a file which another process is using I get an Operating-System error. The file is untouchable until the original process releases it's lock on the file. That was great back in the single-user days of MS-DOS when any locking process was likely to be on the same computer that contained the files, however on a network it's a nightmare:

考虑在写入 Windows 文件服务器上的共享文件时进程挂起时会发生什么.在删除文件之前,我们必须找到计算机并标识该计算机上最初打开文件的进程.只有这样我们才能终止进程并删除我们不需要的文件.

Consider what happens when a process hangs while writing to a shared file on a Windows file-server. Before the file can be deleted we have to locate the computer and ID the process on that computer which originally opened the file. Only then can we kill the process and delete our unwanted file.

真麻烦!

有没有办法让它变得更好?我想要的是 Windows 上的文件锁定行为类似于 UNIX 中的文件锁定.我希望操作系统让我做我想做的事,因为我负责并且我知道我在做什么......

Is there a way to make this better? What I want is for file-locking on Windows to behave a like file-locking in UNIX. I want the operating system to just let me do what I want because I'm in charge and I know what I'm doing...

...所以可以吗?

推荐答案

根据 MSDN 你可以指定 CreateFile() 第三个参数 (dwSharedMode) 共享模式标志 FILE_SHARE_DELETE 其中:

According to MSDN you can specify to CreateFile() 3rd parameter (dwSharedMode) shared mode flag FILE_SHARE_DELETE which:

启用对文件或设备的后续打开操作以请求删除访问权限.

Enables subsequent open operations on a file or device to request delete access.

否则,如果其他进程请求删除访问权限,它们将无法打开文件或设备.

Otherwise, other processes cannot open the file or device if they request delete access.

如果未指定此标志,但已打开文件或设备进行删除访问,则函数失败.

If this flag is not specified, but the file or device has been opened for delete access, the function fails.

注意删除访问允许删除和重命名操作.

Note Delete access allows both delete and rename operations.

http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx

因此,如果您可以控制自己的应用程序,则可以使用此标志.

So if you're can control your applications you can use this flag.

这篇关于如何使 Windows 文件锁定更像 UNIX 文件锁定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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