How to check whether a file is locked in Cocoa?

后端 未结 3 1511
南方客
南方客 2021-02-06 15:47

Is there any API to check whether a file is a locked? I am not able to find any API in the NSFileManager class.Let me know if there is any API to check the lock of

3条回答
  •  攒了一身酷
    2021-02-06 16:32

    I don't really know the answer to this question as I don't know how OS X implements its locking mechanism.

    It might use the POSIX advisory locking as documented in the flock() manpage and if I were you I would write a 10 31-line test program in C to show what fcntl() (manpage) thinks about the advisory lock you have made from within Finder.

    Something like (untested):

    #include 
    #include 
    #include 
    
    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;
    }
    

提交回复
热议问题