Ben-xue
Ben-xue

Reputation: 103

multiprocess open a same file cause file operation failed

During process running , I use vim aa.txt and exec :wq ,then this process can't print any longer. Why ?

When I check process status by lsof -p pid,It show /home/ben/bypy/sederror/aa.txt~ (deleted) . By the way , testing in 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;
}

Upvotes: 2

Views: 101

Answers (1)

When you open a file on Linux, it's identified by device and inode, which isn't reused as long as anything has a reference to it. If you delete the file and create a new one with the same name, any processes that already had it open will still be referring to the old now-deleted one, not the new one. And when you edit files with vi, it doesn't overwrite them in place; it does delete the old one and make a new one.

Upvotes: 5

Related Questions