func exclusiveAccess()

in Sources/XCRemoteCache/Stats/ExclusiveFileAccessor.swift [63:86]


    func exclusiveAccess<T>(block: (FileHandle) throws -> (T)) throws -> T {
        // Read, write
        // mode (if the file is not existing: 0x444)
        let chmod = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH
        let fd = open(fileURL.path, extraFlags | O_RDWR, chmod)
        guard fd > 0 else {
            throw FileAccessorError.openingFailure
        }
        let handle = FileHandle(fileDescriptor: fd)
        defer {
            // closing releases a lock form `flock` (if is set)
            handle.closeFile()
        }
        guard flock(fd, LOCK_EX) == 0 else {
            throw FileAccessorError.lockingFailure
        }
        // While having a lock, make sure the file still exists
        // It might delete it while we were waiting for a lock
        guard access(fileURL.path, F_OK) == 0 else {
            throw FileAccessorError.lockingFailure
        }

        return try block(handle)
    }