Wait for file removal after close

459 Views Asked by At

I'm working on a quota manager implemented in C/C++ under OS X that limit the maximum size of a specific folder. In my project there are generic thread workers that may perform either writing new data to the folder or moving data from the folder to server.

This way, sometimes, a removing task may delete a file that is still in the process of being written into the disk by another thread.

can I somehow prevent the file from being remove during writing process. I can implement mechanism of my own (using flags, locks, etc...) but i believe it should be filesystem property.

I've tried the following code to check if remove fails of the file is still opened, but it actually succeed.

#include <stdio.h> 
int main() {
    FILE *fp;
    fp=fopen("./x", "w");
    fprintf(fp, "Testing...\n");
    if( remove( "./x" ) != 0 )
        perror( "Error deleting file" );
    else
        puts( "File successfully deleted" );
    return 0;
}

how can i enfoce file closed before deleting ?

2

There are 2 best solutions below

2
On BEST ANSWER

Use the lsof command to check which are the files open. (lsof - list open files)

For example you can invoke lsof with -F p and it will output the pid of the processes prefixed with 'p':

$ lsof -F p /some/file
p1234
p4567

Refer : lsof man page

1
On

You can use chattr (See: https://en.wikipedia.org/wiki/Chattr) from preventing the file from being deleted. Read the "Immutable" property.