多进程打开同一个文件导致文件操作失败
在进程运行期间,我使用vim aa.txt和 exec :wq,然后此进程无法再打印。为什么 ?
当我检查进程状态时lsof -p pid,它显示/home/ben/bypy/sederror/aa.txt~ (deleted) . 顺便说一下,在centos中测试。
//test.cc
#include <iostream>
#include <fstream>
#include <unistd.h>
using namespace std;
int main()
{
ofstream file("./aa.txt");
if(!file.is_open())
{
return -1;
}
int iNum = 1;
while(1)
{
file << iNum <<endl;
iNum++;
sleep(5);
}
return 0;
}
回答
当您在 Linux 上打开文件时,它由设备和 inode 标识,只要有任何引用它就不会重用。如果您删除该文件并创建一个具有相同名称的新文件,则任何已经打开该文件的进程仍将引用已删除的旧文件,而不是新文件。当你用 vi 编辑文件时,它不会原地覆盖它们;它确实删除了旧的并创建了一个新的。
- See also [inode(7)](https://man7.org/linux/man-pages/man7/inode.7.html) and [path_resolution(7)](https://man7.org/linux/man-pages/man7/path_resolution.7.html)
- Note that vim does not always delete the old file and create a new one with the same name, but that is the default behavior if the file has only one link.