Why write to a file descriptor after successfully deleting the target file?

the 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 sleep () you delete test.txt, but the process writes successfully, why? if the log instance is "Singleton", you delete the file on the .write disk successfully, but you cannot get anything.

 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" cannt solve this problem.

+6
source share
1 answer

The man page for unlink (2) clearly states:

unlink() removes the name from the file system. If this name was the last link to the file, and no processes open the file, the file is deleted, and the space that it used becomes available for reuse.

If the name was the last link to the file, but all processes still have an open file, the file will remain in memory until the last file, the handle that refers to it is closed .

As the caf perfectly notes in the comments:

Writing () is successful because it writes to a file that still exists at that moment, even if it no longer has a name. The file name and the file itself are different and have separate lifetimes.

+12
source

Source: https://habr.com/ru/post/903170/


All Articles