I have a process using C on Linux OS that writes data to a file. It uses open()/write() functions and I’ve been wondering if another process rm‘d or mv‘d the file. How can my process find out and recreate the file?
I have a process using C on Linux OS that writes data to a
Share
You can use
fstat()to get the information about the open file. If thest_nlinkfield is zero, the file has been removed from the file system (possibly by being moved to a different file system, but there’s no real way for you to determine that). There’s a decent chance you have the only remaining reference to that file – though there might be other processes also holding it open. The disk space won’t be released until the last process with an open file descriptor for the file finally closes the file.If the
st_nlinkfield is still positive, then your file still has a name somewhere out in the file system. You then need to usestat()to determine whether thest_devandst_inofields for the given file name match the same fields from the file descriptor. If the name still exists and has the same device and inode number, then it is ‘the same’ file (though the contents may have changed). If there’s a difference, then the open file is different from the file specified by name.Note that if you want to be sure that the given name is not a symbolic link to a moved copy of the file, then you would have to use
lstat()on the file when you open it (to ensure it isn’t a symlink at that point), and again when you check the file (instead of usingstat()).