From 6743e4e3b03cd3e8175a11f328e530edd054f2f1 Mon Sep 17 00:00:00 2001 From: Meghan Denny Date: Sun, 31 May 2026 14:47:27 -0700 Subject: [PATCH] Dir: allow openFile to acquire a lock --- Dir.zig | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/Dir.zig b/Dir.zig index b12a540b3b2da8bc11652bed6fcecd1134ab11a9..07544faac4fc4c137e70837b0002735f7d7e29fd 100644 --- a/Dir.zig +++ b/Dir.zig @@ -29,8 +29,19 @@ pub fn openFile(self: Dir, sub_path: [:0]const u8, flags: OpenFileFlags) !File { .write_only => sys.O.WRONLY, .read_write => sys.O.RDWR, }; + if (os != .linux) oflag |= switch (flags.lock) { + .none => 0, + .shared => sys.O.SHLOCK, + .exclusive => sys.O.EXLOCK, + }; oflag |= sys.O.CLOEXEC; - return .{ .fd = @enumFromInt(try sys.openat(@intFromEnum(self.fd), sub_path.ptr, oflag)) }; + const fd = try sys.openat(@intFromEnum(self.fd), sub_path.ptr, oflag); + if (os == .linux) switch (flags.lock) { + .none => {}, + .shared => try sys.flock(fd, sys.LOCK.SH), + .exclusive => try sys.flock(fd, sys.LOCK.EX), + }; + return .{ .fd = @enumFromInt(fd) }; } pub fn openFileC(self: Dir, sub_path: []const u8, flags: OpenFileFlags) !File { std.debug.assert(sub_path.len <= sys.PATH_MAX); @@ -42,6 +53,7 @@ pub fn openFileC(self: Dir, sub_path: []const u8, flags: OpenFileFlags) !File { pub const OpenFileFlags = packed struct { mode: enum(u8) { read_only, write_only, read_write } = .read_only, + lock: enum(u8) { none, shared, exclusive } = .none, }; pub fn openDir(self: Dir, sub_path: [:0]const u8, flags: OpenDirFlags) !Dir { -- 2.54.0