Removing a possibly locked file in c

I am using fcntl locks in C on linux and have the dilemma of trying to delete a file that might be locked from other processes that also check the fcntl locking mechanism. What would be the preferred way to handle this file that needs to be deleted (Should I just delete the file without considering other processes that might have a reader lock, or is there a better way)? Any help would be much appreciated.

+2


a source to share


3 answers


On UNIX systems, you can detach a file while it is still open; this decreases the link count of the file, but the actual file and its inode remain around until the link count reaches zero.



+2


a source


As others have noted, you can delete a file even while it is locked.

Now, please note, you didn't mention why processes are blocking this file, but you should be aware that if you are using this file for interprocess synchronization, deleting it is a good way to introduce subtle race conditions into your system, mainly because there is no way atomically create AND lock a file in one operation.



For example, an AA process might create a file with the intent to immediately lock it to do whatever it needs to do. However, there is nothing to stop the BB process from first acquiring the lock on the file and then deleting the file, leaving the AA process with the now deleted file descriptor. The AA process will still be able to lock and update this file, but those updates will be effectively "lost" because the file has already been deleted.

+1


a source


In addition, locks on UNIX are optional by default, so locking a file does not prevent it from being opened or disconnected, just from being relocked.

0


a source







All Articles