gpt4 book ai didi

macos - 如何检测文件是否被关闭?

转载 作者:行者123 更新时间:2023-12-03 17:12:21 24 4
gpt4 key购买 nike

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

FSEvents API 不会触发此类事件。

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

最佳答案

是的,有一种方法可以查明文件是否已关闭。所以下面我尝试使用 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");
}

关于macos - 如何检测文件是否被关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19181005/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com