aboutsummaryrefslogtreecommitdiff
path: root/toys/sleep.c
blob: ed8523f3072038ac163b965dd7ae90160a2f2778 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/* vi: set sw=4 ts=4:
 *
 * sleep.c - Wait for a number of seconds.
 *
 * Copyright 2007 Rob Landley <rob@landley.net>
 * Copyright 2012 Georgi Chorbadzhiyski <georgi@unixsol.org>
 *
 * See http://www.opengroup.org/onlinepubs/009695399/utilities/sleep.html

USE_SLEEP(NEWTOY(sleep, "<1", TOYFLAG_BIN))

config SLEEP
	bool "sleep"
	default y
	help
	  usage: sleep SECONDS

	  Wait before exiting.

config SLEEP_FLOAT
	bool
	default y
	depends on SLEEP && TOYBOX_FLOAT
	help
	  The delay can be a decimal fraction. An optional suffix can be "m"
	  (minutes), "h" (hours), "d" (days), or "s" (seconds, the default).
*/

#include "toys.h"

void sleep_main(void)
{

	if (!CFG_TOYBOX_FLOAT) toys.exitval = sleep(atol(*toys.optargs));
	else {
		char *arg;
		double d = strtod(*toys.optargs, &arg);
		unsigned long l;

		// Parse suffix
		if (*arg) {
			int imhd[]={60,3600,86400};
			char *mhd = "mhd", *c = strchr(mhd, *arg);
			if (!arg) error_exit("Unknown suffix '%c'", *arg);
			d *= imhd[c-mhd];
		}

		// wait through the delay
		l = (unsigned long)d;
		d -= l;
		if (l) toys.exitval = sleep(l);
		if (!toys.exitval) {
			unsigned long usec = d * 1000000;
			struct timespec tv = {
				.tv_sec = usec / 1000000,
				.tv_nsec = (usec % 1000000) * 1000
			};
			toys.exitval = nanosleep(&tv, NULL);
		}
	}
}