bin/sleep: add support for units other than seconds

The coreutils version of this command accepts a unit designation of s,
m, h, or d (for seconds, minutes, hours, days) immediately following
the number of (fractional) units to delay.

The submitted patch has been modified in one detail: the test meant to
detect the presence of the unit modified was not specific (!= 1) and
would have accepted a non-numeric initial element or extra characters
following the union. The committed version accepts only the number
immediately followed by one of the defined unit designators and no
further characters.

PR:		264162
MFC after:	1 week
This commit is contained in:
A. Mallory 2022-05-24 09:43:38 +02:00 committed by Stefan Eßer
parent cdcd52d41e
commit 34978f7edd
2 changed files with 25 additions and 5 deletions

View file

@ -40,13 +40,21 @@
.Nd suspend execution for an interval of time
.Sh SYNOPSIS
.Nm
.Ar seconds
.Ar number[unit]
.Sh DESCRIPTION
The
.Nm
command
suspends execution for a minimum of
.Ar seconds .
.Ar number
seconds (the default, or unit
.Ar s ) ,
or minutes (unit
.Ar m ) ,
hours (unit
.Ar h ) ,
or days (unit
.Ar d ) .
.Pp
If the
.Nm

View file

@ -66,6 +66,7 @@ main(int argc, char *argv[])
struct timespec time_to_sleep;
double d;
time_t original;
char unit;
char buf[2];
if (caph_limit_stdio() < 0 || caph_enter() < 0)
@ -74,8 +75,17 @@ main(int argc, char *argv[])
if (argc != 2)
usage();
if (sscanf(argv[1], "%lf%1s", &d, buf) != 1)
usage();
if (sscanf(argv[1], "%lf%c%1s", &d, &unit, buf) == 2)
switch(unit) {
case 'd': d *= 24;
case 'h': d *= 60;
case 'm': d *= 60;
case 's': break;
default: usage();
}
else
if (sscanf(argv[1], "%lf%1s", &d, buf) != 1)
usage();
if (d > INT_MAX)
usage();
if (d <= 0)
@ -106,6 +116,8 @@ static void
usage(void)
{
fprintf(stderr, "usage: sleep seconds\n");
fprintf(stderr, "usage: sleep number[unit]\n");
fprintf(stderr, "Unit can be 's' (seconds, the default), "
"m (minutes), h (hours), or d (days).\n");
exit(1);
}