]> git.lizzy.rs Git - uwu-nolambda.git/blob - os.c
Fix typo in README.md
[uwu-nolambda.git] / os.c
1 #include <time.h>
2 #include <stdlib.h>
3 #include <errno.h>
4 #include "api/vm.h"
5 #include "api/util.h"
6 #include "api/int.h"
7 #include "api/nil.h"
8 #include "api/str.h"
9 #include "common/err.h"
10
11 UwUVMValue uwu_exit(UwUVMArgs *args)
12 {
13         uwuutil_require_max("os.exit", args, 1);
14
15         long exit_code = 0;
16
17         if (args->num == 1)
18                 exit_code = uwuint_get(uwuvm_get_arg(args, 0));
19
20         exit(exit_code);
21         return uwunil_create();
22 }
23
24 UwUVMValue uwu_sleep(UwUVMArgs *args)
25 {
26         uwuutil_require_exact("os.sleep", args, 1);
27
28         UwUVMValue value = uwuvm_get_arg(args, 0);
29
30         if (value.type != &uwuint_type)
31                 error("type error: os.sleep requires an integer as $1\n");
32
33         long millis = uwuint_get(value);
34
35         if (millis < 0)
36                 error("type error: os.sleep requires a positive value as $2\n");
37
38         struct timespec ts = {
39                 .tv_sec = millis / 1000,
40                 .tv_nsec = 1000000 * (millis % 1000),
41         };
42
43         while (nanosleep(&ts, &ts) != 0)
44                 if (errno != EINTR)
45                         syserror("nanosleep", NULL);
46
47         return uwunil_create();
48 }
49
50 UwUVMValue uwu_execute(UwUVMArgs *args)
51 {
52         uwuutil_require_exact("os.execute", args, 1);
53
54         char *command = uwustr_get(uwuvm_get_arg(args, 0));
55         int ret = system(command);
56         free(command);
57
58         return uwuint_create(ret);
59 }
60
61 UwUVMValue uwu_time(UwUVMArgs *args)
62 {
63         uwuutil_require_exact("os.time", args, 0);
64
65         struct timespec ts;
66         clock_gettime(CLOCK_REALTIME, &ts);
67
68         return uwuint_create(ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
69 }