How to detect if a file was closed?

独自空忆成欢 提交于 2019-12-24 15:55:20

问题


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?!


回答1:


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");
}


来源:https://stackoverflow.com/questions/19181005/how-to-detect-if-a-file-was-closed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!