Skip to content

Instantly share code, notes, and snippets.

@marler8997
Last active July 27, 2022 14:26
Show Gist options
  • Save marler8997/7f2e1b6a3ce938285c620c642c3e581a to your computer and use it in GitHub Desktop.
Save marler8997/7f2e1b6a3ce938285c620c642c3e581a to your computer and use it in GitHub Desktop.
How to select in Zig
const std = @import("std");
// NOTE: it's lucky that StaticBitSet has the right memory layout
// it may not in the future or on some platforms
const FdSet = std.StaticBitSet(1024);
comptime {
// make sure our FdSet is right
std.debug.assert(@sizeOf(FdSet) == 1024 / 8);
}
pub fn pselect6(
nfds: isize,
readfds: ?*FdSet,
writefds: ?*FdSet,
exceptfds: ?*FdSet,
timeout: ?*const std.os.linux.timespec,
sigmask: ?*const std.os.linux.sigset_t,
) usize {
return std.os.linux.syscall6(
.pselect6,
@bitCast(usize, nfds),
@ptrToInt(readfds),
@ptrToInt(writefds),
@ptrToInt(exceptfds),
@ptrToInt(timeout),
@ptrToInt(sigmask),
);
}
pub fn main() !void {
const fd1 = 0;
const fd2 = 1;
const maxfd = std.math.max(fd1, fd2) + 1;
while (true) {
var readfds = FdSet.initEmpty();
readfds.setValue(fd1, true);
readfds.setValue(fd2, true);
switch (std.os.errno(pselect6(maxfd, &readfds, null, null, null, null))) {
.SUCCESS => {},
else => |errno| {
std.log.err("select failed, errno={}", .{errno});
std.os.exit(0xff);
},
}
if (readfds.isSet(fd1)) {
var buf: [100]u8 = undefined;
_ = try std.os.read(fd1, &buf);
} else if (readfds.isSet(fd2)) {
var buf: [100]u8 = undefined;
_ = try std.os.read(fd2, &buf);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment