如何检测文件是否已关闭?

时间:2013-10-04 12:19:56

标签: macos cocoa filesystems nsfilemanager fsevents

是否可以检测文件(例如预览中打开的pdf文件)是否已关闭?

FSEvents API不会触发此类事件。

也许我可以观察相关的过程或类似的东西?!

1 个答案:

答案 0 :(得分:1)

是的,您可以通过该方式查看文件是否已关闭。所以下面我尝试使用unix lsof -t yourFilePath命令来确定相同的内容,因此在cocoa中实现了相同的功能。请按照下面的说明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");
}
相关问题