如何检测,如果一个文件被关闭?(How to detect if a file was closed

2019-10-18 18:05发布

是可以检测,如果一个文件(例如,在预览打开PDF文件)被关闭?

FSEvents API不会触发此类事件。

也许我可以看到相关的过程或类似的东西?

Answer 1:

是的,有,你可以找出文件是否已关闭或没有办法的办法。 所以下面我与UNIX试图lsof的-t yourFilePath命令确定不变,因此已实施在可可相同。 请按照以下这里lsof的-t yourFilePath会给你只打开文件的进程ID。 所以,你可以很容易地检测出哪些文件被关闭: -

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


文章来源: How to detect if a file was closed?