import Darwin import Foundation @MainActor final class SingleInstance { private var descriptor: Int32? private let path: String init(path: String) { self.path = path } func claim() throws -> Bool { if descriptor != nil { return true } let fd = Darwin.open(path, O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK, S_IRUSR | S_IWUSR) guard fd >= 0 else { throw AppText.detail("The single-instance check failed: %@", String(cString: strerror(errno))) } var info = stat() guard fstat(fd, &info) == 0, info.st_uid == getuid(), info.st_mode & S_IFMT == S_IFREG, info.st_nlink == 1 else { Darwin.close(fd) throw AppText.failure("The single-instance lock is not a safe file.") } guard flock(fd, LOCK_EX | LOCK_NB) == 0 else { let code = errno Darwin.close(fd) if code == EWOULDBLOCK { return false } throw AppText.detail("The single-instance check failed: %@", String(cString: strerror(code))) } descriptor = fd return true } func release() { if let descriptor { Darwin.close(descriptor) } descriptor = nil } deinit { if let descriptor { Darwin.close(descriptor) } } }