Commit 7e59f4ff69

Andrew Kelley <superjoe30@gmail.com>
2017-09-06 22:59:22
std: add os.sleep
1 parent 1f2548e
Changed files (3)
std/os/index.zig
@@ -924,3 +924,25 @@ pub fn readLink(allocator: &Allocator, pathname: []const u8) -> %[]u8 {
         return result_buf[0..ret_val];
     }
 }
+
+pub fn sleep(seconds: u64, nanoseconds: u64) {
+    var req = posix.timespec {
+        .tv_sec = seconds,
+        .tv_nsec = nanoseconds,
+    };
+    var rem: posix.timespec = undefined;
+    while (true) {
+        const ret_val = posix.nanosleep(&req, &rem);
+        const err = posix.getErrno(ret_val);
+        if (err == 0) return;
+        switch (err) {
+            posix.EFAULT => unreachable,
+            posix.EINVAL => unreachable,
+            posix.EINTR => {
+                req = rem;
+                continue;
+            },
+            else => return,
+        }
+    }
+}
std/os/linux.zig
@@ -459,6 +459,10 @@ pub fn waitpid(pid: i32, status: &i32, options: i32) -> usize {
     arch.syscall4(arch.SYS_wait4, usize(pid), @ptrToInt(status), @bitCast(usize, isize(options)), 0)
 }
 
+pub fn nanosleep(req: &const timespec, rem: ?&timespec) -> usize {
+    arch.syscall2(arch.SYS_nanosleep, @ptrToInt(req), @ptrToInt(rem))
+}
+
 const NSIG = 65;
 const sigset_t = [128]u8;
 const all_mask = []u8 { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, };
std/os/linux_x86_64.zig
@@ -476,6 +476,6 @@ pub const Stat = extern struct {
 };
 
 pub const timespec = extern struct {
-    tv_sec: isize,
-    tv_nsec: isize,
+    tv_sec: usize,
+    tv_nsec: usize,
 };