检查文件是否在另一个进程中打开 [英] Check if a file is open in another process

查看:59
本文介绍了检查文件是否在另一个进程中打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法打开一个非共享独占读写访问的文件?

来自 fs.watch 的文件更改事件并不一定意味着文件已完全写入,在大多数基于节点的进程的情况下,更多的块正在流中,或者可能只是还没有被冲掉.

A file change event from fs.watch does not necessarily mean that the file has been completely written, In the case of most node based processes more chunks are coming down the stream, or it might just not have been flushed yet.

fs.open 允许已打开且正在流式传输的文件以写入模式打开而不会出错.可以引入超时延迟,但这太脆弱和武断了.

fs.open lets a file that is already open and being streamed to be opened, in write mode without an error. One could introduce a timeout delay but that's just too brittle and arbitrary.

在 Windows 上,可以使用 C 中的 FILE_SHARE_NONE 来执行 CreateFile,但不太记得 Linux 上的等效项是什么(因为锁是建议性的,如果我没记错),不知道 OS X 是否有等价的,posix 或其他).

On windows, one would be able to do CreateFile with FILE_SHARE_NONE from C, can't quite recall what the equivalent is on Linux (as locks are advisory if i remember correctly), don't know if OS X has an equivalent, posix or otherwise).

推荐答案

您可以使用 @ronomon/opened 检查文件是否在另一个进程中打开,是否有任何应用程序打开了该文件的句柄或文件描述符.

You can use @ronomon/opened to check if a file is open in another process, if any applications have open handles or file descriptors to the file.

它不会告诉您哪些应用程序打开了该文件,只会告诉您该文件在其他应用程序中已打开.

It won't tell you which applications have the file open, only that the file is open in other applications.

它适用于 Windows、macOS 和 Linux,并且只需要在 Linux 上的权限.

It works on Windows, macOS and Linux and requires privileges only on Linux.

它使用 Windows 上的本机绑定以独占共享模式打开文件,以检测由于其他进程打开句柄引起的任何共享冲突.

It uses a native binding on Windows to open the file with exclusive sharing mode to detect any sharing violations due to other processes with open handles.

在 macOS 和 Linux 上,它包装 lsof.

On macOS and Linux it wraps lsof.

与使用flock等替代方案相比,据我了解,flock只是建议性的,因此只有所有进程合作检查锁才会起作用,如果进程是独立的,大多数时候情况并非如此.

Compared to using an alternative such as flock, as far as I understand, flock is only advisory, so it will only work if all processes cooperate to check the lock, which is not the case most of the time if the processes are independent.

这篇关于检查文件是否在另一个进程中打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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