micro-utils/coreutils/sleep.c

48 lines
828 B
C
Raw Normal View History

2023-10-13 19:33:48 +03:00
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
2023-10-22 09:03:58 +03:00
double convert(const char *num) {
if (atof(num) <= 0) {
fprintf(stderr, "sleep: %s < 1\n", num);
exit(1);
}
return atof(num);
}
2023-10-13 19:33:48 +03:00
int main(const int argc, const char **argv) {
2023-10-22 09:26:38 +03:00
if (argc == 1 || !strcmp(argv[argc - 1], "--help")) {
2023-10-30 18:09:33 +03:00
printf("sleep [num[m - minute / h - hour / d - days]] / [inf infinity]\n");
2023-10-13 19:33:48 +03:00
return 0;
}
if (!strcmp(argv[1], "inf"))
for (;;)
sleep(1);
2023-10-22 09:03:58 +03:00
double sec = 0;
2023-10-13 19:33:48 +03:00
for (int i = 1; i < argc; i++) {
switch (argv[i][strlen(argv[i]) - 1]) {
case 'd':
2023-10-22 09:03:58 +03:00
sec += convert(argv[i]) * 86400;
2023-10-13 19:33:48 +03:00
break;
case 'h':
2023-10-22 09:03:58 +03:00
sec += convert(argv[i]) * 3600;
2023-10-13 19:33:48 +03:00
break;
case 'm':
2023-10-22 09:03:58 +03:00
sec += convert(argv[i]) * 60;
2023-10-13 19:33:48 +03:00
break;
default:
2023-10-22 09:03:58 +03:00
sec += convert(argv[i]);
2023-10-13 19:33:48 +03:00
}
}
2023-10-22 09:03:58 +03:00
usleep(sec * 1000000);
2023-10-13 19:33:48 +03:00
return 0;
}