sleep.c (1164B)
- // utils-std: Collection of commonly available Unix tools
- // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
- // SPDX-License-Identifier: MPL-2.0
- #define _POSIX_C_SOURCE 200809L
- #include "../lib/strtodur.h"
- #include <errno.h> // errno
- #include <stdio.h> // fprintf, perror
- #include <time.h> // nanosleep
- int
- main(int argc, char *argv[])
- {
- struct timespec dur = {.tv_sec = 0, .tv_nsec = 0};
- for(int i = 1; i < argc; i++)
- {
- struct timespec arg_dur = {.tv_sec = 0, .tv_nsec = 0};
- if(strtodur(argv[i], &arg_dur) < 0)
- {
- return 1;
- }
- dur.tv_sec += arg_dur.tv_sec;
- dur.tv_nsec += arg_dur.tv_nsec;
- if(dur.tv_nsec > 999999999)
- {
- dur.tv_nsec = 0;
- dur.tv_sec += 1;
- }
- }
- if(dur.tv_sec == 0 && dur.tv_nsec == 0)
- {
- fprintf(stderr, "sleep: error: Got a total duration of 0\n");
- return 1;
- }
- errno = 0;
- if(nanosleep(&dur, &dur) < 0)
- {
- if(errno == EINTR)
- {
- fprintf(stderr,
- "sleep: warning: Interrupted during sleep, still had %ld.%09ld seconds remaining\n",
- dur.tv_sec,
- dur.tv_nsec);
- }
- else
- {
- perror("sleep: warning: nanosleep");
- }
- }
- return 0;
- }