为什么在删除目标文件后成功写入文件描述符? [英] Why does writing to a file descriptor after the target file has been deleted succeed?

查看:63
本文介绍了为什么在删除目标文件后成功写入文件描述符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

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);
}

在sleep()期间,您删除了test.txt,但是该过程写入成功!为什么?如果日志为"Singleton"实例,则删除磁盘上的文件.写入成功,但是却什么也没得到.

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.

推荐答案

unlink()从文件系统中删除一个名称.如果那个名字是文件的最后一个链接,没有进程打开该文件是删除,并且可以重复使用它.

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.

caf 在注释中很好地指出:

As caf excellently notes in the comments:

write()成功,因为它写入文件,该文件仍然即使它不再具有名称,此刻也存在.档名并且文件本身是不同的,并且具有不同的生存期.

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.

这篇关于为什么在删除目标文件后成功写入文件描述符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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