0

Is it possible to prevent file deletion/renaming while program has opened file descriptor. I open file with open() and then try locking it with fcntl() but i still can rename or delete file. Reading fcntl documentation it seems imposible to do.

FD = open(file_name, O_WRONLY | O_CREAT | O_EXCL, 0600);
struct flock exclusiveLock;
exclusiveLock.l_type=F_WRLCK;
exclusiveLock.l_whence=SEEK_SET;
exclusiveLock.l_len=exclusiveLock.l_start=0;
exclusiveLock.l_pid=0;
lockResult=fcntl(FD,F_SETLK,&exclusiveLock);
user1188351
  • 93
  • 2
  • 10
  • Why do you care? It's not like the file will disappear on you, since its reference count will remain above zero due to your file descriptor being open. – EOF Sep 28 '15 at 15:18
  • Yes, i read that descriptor remains valid. But its daemon lock file with PID in it. So when file deleted, i cannot get PID anymore to stop it or send command. – user1188351 Sep 28 '15 at 15:21
  • I don't know if it helps but this article provides a way to lock a file. However, it needs some modifications on the filesystem during the mount in order to support the lock/unlock operations: http://www.thegeekstuff.com/2012/04/linux-file-locking-types/ – rkachach Sep 28 '15 at 15:26
  • 1
    As long as there is a reference to the file, it will not be deleted. What you might know from Windows that the filename is part of the file is not true in Linux. The filename is just another reference (a permanent one, but neverless not "the file"). If you need the file to be accessible from a filename, you just shall not `unlink` the latter. Why would one do this anyway? Don't try to outsmart your OS. – too honest for this site Sep 28 '15 at 15:32
  • Can you change the process that is doing unwanted renames and unlinks so that it checks for a lock first? – Mark Plotnick Sep 28 '15 at 15:48
  • 1
    See here: http://stackoverflow.com/a/32585700/3169754 TL;DR: No, you can't prevent file from renaming/unlinking, unless the process that calls rename/unlink knows that it should lock the file before trying to rename/unlink it. – gavv Sep 28 '15 at 16:05

0 Answers0