Function tryLock [src]

Attempts to obtain a lock, returning true if the lock is obtained, and false if there was an existing incompatible lock held. A process may hold only one type of lock (shared or exclusive) on a file. When a process terminates in any way, the lock is released. Assumes the file is unlocked. TODO: integrate with async I/O

Prototype

pub fn tryLock(file: File, l: Lock) LockError!bool

Parameters

file: Filel: Lock

Possible Errors

FileLocksNotSupported
SystemResources
Unexpected UnexpectedError

The Operating System returned an undocumented error code.

This error is in theory not possible, but it would be better to handle this error than to invoke undefined behavior.

When this error code is observed, it usually means the Zig Standard Library needs a small patch to add the error code to the error set for the respective function.

Source

pub fn tryLock(file: File, l: Lock) LockError!bool { if (is_windows) { var io_status_block: windows.IO_STATUS_BLOCK = undefined; const exclusive = switch (l) { .none => return, .shared => false, .exclusive => true, }; windows.LockFile( file.handle, null, null, null, &io_status_block, &range_off, &range_len, null, windows.TRUE, // non-blocking=true @intFromBool(exclusive), ) catch |err| switch (err) { error.WouldBlock => return false, else => |e| return e, }; } else { posix.flock(file.handle, switch (l) { .none => posix.LOCK.UN, .shared => posix.LOCK.SH | posix.LOCK.NB, .exclusive => posix.LOCK.EX | posix.LOCK.NB, }) catch |err| switch (err) { error.WouldBlock => return false, else => |e| return e, }; } return true; }