如何故意让文件处于「EBUSY: resource busy or locked」状态?
嘿,我刚好研究过这个问题!要故意触发「EBUSY: resource busy or locked」错误,核心就是让文件被独占占用——要么通过文件锁,要么用系统级的独占打开模式。下面给你详细的方案,优先NodeJS的:
NodeJS 实现方案
方法1:跨平台文件独占锁(推荐)
Node.js 从 v14.18.0 开始原生支持文件锁 API,通过给文件加独占锁,能让其他进程/操作完全无法访问该文件,直接触发 EBUSY 错误。
代码示例:
const fs = require('fs').promises; const path = require('path'); async function lockFileForEBUSY() { const targetFile = path.resolve('./test-lock-file.txt'); // 先确保文件存在(如果不存在就创建) await fs.writeFile(targetFile, 'placeholder content'); // 打开文件获取句柄 const fileHandle = await fs.open(targetFile, 'r+'); try { // 给整个文件加独占锁('ex' 代表 exclusive lock) await fileHandle.lock('ex'); console.log('✅ 文件已被独占锁定!保持这个进程运行,去其他终端/程序尝试修改/删除该文件,就能触发 EBUSY 错误'); // 让进程一直运行,直到用户输入任意内容 await new Promise(resolve => process.stdin.on('data', resolve)); } finally { // 退出时记得解锁并关闭文件句柄 await fileHandle.unlock(); await fileHandle.close(); } } lockFileForEBUSY().catch(err => console.error('出错了:', err));
运行这段代码后,在另一个终端执行rm test-lock-file.txt或者echo "new text" > test-lock-file.txt,马上就能看到EBUSY错误。
方法2:Windows 专属独占打开模式
如果你只需要在Windows系统上实现,不用锁API也能做到——Windows文件系统支持完全独占打开,只要打开文件时不允许任何共享权限,其他进程碰这个文件就会报错。
代码示例:
const fs = require('fs'); const path = require('path'); const targetFile = path.resolve('./test-win-file.txt'); // 先创建文件 fs.writeFileSync(targetFile, 'windows test content'); // 打开文件时设置共享模式为0(不允许任何共享) fs.open(targetFile, 'r+', { share: 0 }, (err, fd) => { if (err) { console.error('打开失败:', err); return; } console.log('✅ 文件已独占打开!其他操作会触发EBUSY,按任意键退出'); // 保持进程运行,直到用户输入 process.stdin.on('data', () => { fs.close(fd, () => process.exit()); }); });
这个方案在Windows上直接生效,不需要依赖高版本NodeJS的锁API。
其他语言/工具方案
Python 实现
用Python结合Windows API可以快速实现独占锁定(跨平台的话也可以用fcntl模块,但Windows需要额外处理):
import os import sys import win32file # 需要先安装pywin32:pip install pywin32 target_file = './test-python-file.txt' # 创建文件 with open(target_file, 'w') as f: f.write('python test content') # 打开文件获取句柄 fd = os.open(target_file, os.O_RDWR) os_handle = win32file._get_osfhandle(fd) # 设置文件为完全独占(不允许任何共享) win32file.SetFileInformationByHandle(os_handle, win32file.FileShareInfo, 0) print('✅ 文件已独占锁定!按任意键退出') sys.stdin.read(1) # 清理资源 os.close(fd)
Windows PowerShell 脚本
不想写代码的话,用PowerShell也能快速实现:
$filePath = ".\test-powershell-file.txt" # 创建测试文件 "powershell test content" | Out-File $filePath # 以完全独占模式打开文件(不允许读/写共享) $fileStream = [System.IO.File]::Open( $filePath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None ) Write-Host "✅ 文件已独占打开!其他操作会触发EBUSY,按任意键退出" $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") # 关闭流 $fileStream.Close()
内容的提问来源于stack exchange,提问作者Pedro A
相关产品推荐
相关产品推荐

