Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does writing to a file descriptor after the target file has been deleted succeed?

Tags:

c

linux

code:

int main(int argc, char **argv)
{
    int fd = open("test.txt", O_CREAT|O_RDWR, 0200|0400);
    if(fd == -1)
    {
        printf("failure to oepn");
        exit(-1);
    }
    int iRet = write(fd, "aaaaaaaaaa", 10);

    if(iRet == -1)
    {
        printf("failure to writer");
        exit(-1);
    }
    sleep(10);
    printf("You must remove");
    iRet = write(fd, "bbbbbbbbbb", 10);

    if(iRet == -1)
    {
        printf("failure to after writer");
        exit(-1);
    }

   exit(0);
}

during the sleep(), you delete the test.txt, but the process write successful!why? if a log ”Singleton“ instance, you remove the file on the disk.write is successful, but you can get nothing.

class log
{
public:
    void loggerWriter(std::string str);
    int fd;
};

log::log(std::string filename):fd(-1)
{
    fd = open(filename.c_str(), O_CREAT|)
    //...
}

log::loggerWriter(std::string str)
{
    writer(fd, str.c_str(), str.size());
}

int main()
{
    log logger("text.txt");
    //...
    //I want to know the text.txt the text.txt have delete on the disk or not.
    //if delete i can create another file to log. 
}

"unlink" cann't solve this problem.

like image 610
OCaml Avatar asked Dec 06 '11 07:12

OCaml


1 Answers

The manual page for unlink(2) states clearly:

unlink() deletes a name from the file system. If that name was the last link to a file and no processes have the file open the file is deleted and the space it was using is made available for reuse.

If the name was the last link to a file but any processes still have the file open the file will remain in existence until the last file descriptor referring to it is closed.

As caf excellently notes in the comments:

The write() is successful because it writes to the file, which still exists at this point even though it no longer has a name. The filename and the file itself are distinct, and have separate lifetimes.

like image 69
cnicutar Avatar answered Sep 21 '22 20:09

cnicutar