本文介绍了为什么在删除目标文件后成功写入文件描述符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码:
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(2)的手册页明确指出:
如果名称是文件的最后链接,但任何进程仍具有文件打开文件将一直存在,直到最后一个文件引用它的描述符已关闭.
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:
这篇关于为什么在删除目标文件后成功写入文件描述符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!