【问题标题】:How to check whether a file is locked in Cocoa?如何检查文件是否在 Cocoa 中被锁定?
【发布时间】:2012-07-29 02:01:25
【问题描述】:

是否有任何 API 可以检查文件是否被锁定?我在 NSFileManager 类中找不到任何 API。如果有任何 API 可以检查文件的锁定,请告诉我。

我找到了以下与文件锁定相关的链接

http://lists.apple.com/archives/cocoa-dev/2006/Nov/msg01399.html

我可以调用 – isWritableFileAtPath: on file。有没有其他方法可以查看文件是否被锁定?

【问题讨论】:

  • 什么样的锁定? POSIX 锁定或更高级别的锁定(我不知道它的名称)?
  • @trojanfoe:我不太确定锁定。可能是 POSIX。我使用finder锁定了文件。我想检查我的应用程序中锁定的文件。

标签: objective-c macos cocoa nsfilemanager


【解决方案1】:

以下代码对我有用。

NSError * error;
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error];
BOOL isLocked = [[attributes objectForKey:NSFileImmutable] boolValue];
            
if (isLocked) {
    NSLog(@"File is locked");
}

【讨论】:

  • 您可以使用 NSFileImmutable 常量,而不是对字符串进行硬编码,我将在其中进行编辑。
【解决方案2】:

我真的不知道这个问题的答案,因为我不知道 OS X 是如何实现其锁定机制的。

可能使用 flock() manpage 中记录的 POSIX 咨询锁定,如果我是你,我会编写一个 10 31 行测试程序C 显示 fcntl() (manpage) 对您在 Finder 中创建的咨询锁的看法。

类似的东西(未经测试):

#include <fcntl.h>
#include <errno.h>
#include <stdio.h>

int main(int argc, const char **argv)
{
    for (int i = 1; i < argc; i++)
    {
        const char *filename = argv[i];
        int fd = open(filename, O_RDONLY);
        if (fd >= 0)
        {
            struct flock flock;
            if (fcntl(fd, F_GETLK, &flock) < 0)
            {
                fprintf(stderr, "Failed to get lock info for '%s': %s\n", filename, strerror(errno));
            }
            else
            {
                // Possibly print out other members of flock as well...
                printf("l_type=%d\n", (int)flock.l_type);
            }
            close(fd);
        }
        else
        {
            fprintf(stderr, "Failed to open '%s': %s\n", filename, strerror(errno));
        }
    }
    return 0;
}

【讨论】:

  • OS X 文件锁定/不可变是一个文件标志(见我的回答)
  • 关于木马的未经测试的代码,现在已经测试过了:)发现还需要一行。在调用 fcntl 之前,你需要告诉它你在寻找什么样的锁。通常,使用flock.l_type = F_WRLCK;其中 F_WRLCK 表示要查找读取或写入(也称为独占)锁。
【解决方案3】:

如有必要,也可以使用 POSIX C 函数确定不可变标志(OS X '文件锁定')。不可变属性不是 unix 术语中的锁,而是文件标志。可以通过stat函数获取:

struct stat buf;
stat("my/file/path", &buf);
if (0 != (buf.st_flags & UF_IMMUTABLE)) {
     //is immutable
}

参考见:https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man2/stat.2.html

不可变标志可以使用chflags函数设置:

chflags("my/file/path", UF_IMMUTABLE);

参考见:https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man2/chflags.2.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多