3

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 ?

Zohar81
  • 4,554
  • 5
  • 29
  • 82
  • You may be interested in [this](http://stackoverflow.com/questions/230062/whats-the-best-way-to-check-if-a-file-exists-in-c-cross-platform). – sjsam May 08 '16 at 10:04
  • Perhaps you may take a look at [this SO post](http://stackoverflow.com/questions/5769785/removing-a-file-in-c) and the [man page](http://linux.die.net/man/3/remove). – user3078414 May 08 '16 at 10:25

2 Answers2

1

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

Ani Menon
  • 27,209
  • 16
  • 105
  • 126
  • Hi, that's a good method. however, i need it programmatically. perhaps you know of C/C++ api to check it a file is opened ? – Zohar81 May 08 '16 at 10:28
  • Read through the **Output for other programs** section on the [man page](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man8/lsof.8.html). It says you will need a header `lsof_fields.h`. – Ani Menon May 08 '16 at 10:53
0

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

rhcw
  • 69
  • 5
  • Hi, thanks for you proposal. however, i wonder if there's any way to set the 'immutable' attribute using C/C++ api right upon opening the file. Moreover, it seems that immutable properly is enforced also on the setter, and i want to continue writing to the file, and only prevent deletion. – Zohar81 May 08 '16 at 10:33