Question

is it possible to detect if a file (e.g. a pdf file opened in preview) was closed?

The FSEvents API does not fire such an event.

Maybe I could observe the associated process or something like that?!

Was it helpful?

Solution

Yes there is the way that you can find out whether file has been closed or not. So below i tried with unix lsof -t yourFilePath command to determine the same and hence have implemented the same in cocoa. Please follow below here lsof -t yourFilePath will give you the process id of only open files. So that you can easily detect which files are closed:-

NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/bin/bash"];
NSString *yourFilePath=@"/Users/Home/Desktop/test.doc";
[task setArguments:[NSArray arrayWithObjects: @"-c",[NSString stringWithFormat:@"%@ %@ %@",@"lsof",@"-t",yourFilePath],nil]];
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];

NSFileHandle *file;
file = [pipe fileHandleForReading];

[task launch];

NSData *data;
data = [file readDataToEndOfFile];
NSString *response = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
if ([response length] > 0)
{
NSLog(@"test.doc file has been opened and process id is %@",response);
}
else
{
NSLog(@"test.doc file has been closed");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top