c - 为什么在删除目标文件后写入文件描述符会成功?

标签 c linux

代码:

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,但是进程写入成功了!为什么? 如果是日志“单例”实例,你删除磁盘上的文件。写入成功,但你什么也得不到。

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. 
}

“取消链接”不能解决这个问题。

最佳答案

manual page for unlink(2)明确指出:

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在评论中出色地指出:

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.

关于c - 为什么在删除目标文件后写入文件描述符会成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8396436/

相关文章:

检查您是否位于主目录(linux)

c++ - 链接可变函数调用

linux - sed 在没有模式匹配时没有输出

C:从文件中读取未知数量的未知长度的行

c - 这段代码是如何占用内存的?

c - 尝试移动到链表的下一个元素时出错

java - 使用 20 M 记录的 Lucene 索引需要更多时间

c++ - 在linux makefile上运行MPI程序

linux - 如何从分析器中获取每个样本的完整堆栈转储以用于火焰图?

Linux如何将时间格式转换为纪元时间?