bug-coreutils
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

PATCH: random sleep modification


From: Phil Tanguay
Subject: PATCH: random sleep modification
Date: Thu, 20 Mar 2003 17:13:29 -0500 (EST)

Hello!

I would like to submit for inclusion a small modification I made to the sleep
program to allow sleep to pause for a random # of seconds, up to the # of
seconds specified (or whatever time suffix was specified).  The random mode is
invoked by adding the -r command line parameter.

It's a rather peculiar need, no doubt.  I use it as part of a home automation
system, where I do not want to turn off and on lights at the exact same time
every day.  I have cron job that gets invoked at a set time, but I then sleep
for a random amount of minutes before performing the actual command.  I'm sure
it might be useful in other contexts as well.  It certainly has been useful to
me so far.

Here is the unified diff of my modification, against version 4.5.11 of
coreutils.  Feedback [good or bad] appreciated.

Keep up the great work!
-Phil

--- sleep.c.orig        Sat Mar  8 09:27:39 2003
+++ sleep.c     Thu Mar 20 17:00:04 2003
@@ -17,6 +17,7 @@
 
 #include <config.h>
 #include <stdio.h>
+#include <stdlib.h>
 #include <assert.h>
 #include <sys/types.h>
 #include <getopt.h>
@@ -50,12 +51,14 @@
   else
     {
       printf (_("\
-Usage: %s NUMBER[SUFFIX]...\n\
+Usage: %s [-r] NUMBER[SUFFIX]...\n\
   or:  %s OPTION\n\
 Pause for NUMBER seconds.  SUFFIX may be `s' for seconds (the default),\n\
 `m' for minutes, `h' for hours or `d' for days.  Unlike most implementations\n\
 that require NUMBER be an integer, here NUMBER may be an arbitrary floating\n\
 point number.\n\
+The -r modifier will cause the pause to be random between 1 and NUMBER 
seconds,\n\
+or SUFFIX if specified.\n\
 \n\
 "),
              program_name, program_name);
@@ -107,6 +110,7 @@
 int
 main (int argc, char **argv)
 {
+       char r=0;
   int i;
   double seconds = 0.0;
   int c;
@@ -122,12 +126,15 @@
   parse_long_options (argc, argv, PROGRAM_NAME, GNU_PACKAGE, VERSION,
                      AUTHORS, usage);
 
-  while ((c = getopt_long (argc, argv, "", long_options, NULL)) != -1)
+  while ((c = getopt_long (argc, argv, "r", long_options, NULL)) != -1)
     {
       switch (c)
        {
        case 0:
          break;
+       case 'r':
+    r = 1;
+     break;
 
        default:
          usage (EXIT_FAILURE);
@@ -161,7 +168,10 @@
 
   if (fail)
     usage (EXIT_FAILURE);
-
+  if  (r) {
+         srand( time( NULL ) );
+         seconds = 1.0 + seconds * rand() / (RAND_MAX+1.0);
+  }
   if (xnanosleep (seconds))
     error (EXIT_FAILURE, errno, _("cannot read realtime clock"));
 





reply via email to

[Prev in Thread] Current Thread [Next in Thread]