Running a script every second

Michael Conrad mconrad at intellitree.com
Thu Mar 6 19:34:25 UTC 2014


I know this borders on bike-shedding, but if you really want to run 
something exactly 60 times per elapsed minute you need to compare calls 
to clock_gettime(CLOCK_MONOTONIC).  Nothing else will work reliably in 
all cases, and certainly not signals.  (if the system is lagged 
significantly, two signals can be merged into one)

I'm not aware of any way to call clock_gettime from a shell script, but 
Perl can do it.  If you don't have perl and you still want it to be a 
script for ease-of-maintenance, I would recommend:

   1. write a very small C program that calls clock_gettime() for an 
initial timestamp, writes "\n" on STDOUT, increment timestamp by exactly 
1 second, calls clock_gettime(), and then usleep()s for the difference 
between clock_gettime and timestamp, if greater than 0.

   2. write a script that performs "./c_prog | while read; do 
something(); done"

No special file descriptors, process IDs, signals or other mess, and 
guaranteed one iteration of the script per every elapsed second (but no 
guarantee that the execution occurs during that second.  Linux isn't 
realtime, afterall)

-Mike

On 3/6/2014 9:25 AM, Yan Seiner wrote:
>
> On 03/05/2014 10:49 PM, Harald Becker wrote:
>> Hi Yan !
>>
>> On 05-03-2014 09:14 Yan Seiner <yan at seiner.com> wrote:
>>> I am trying to run a script every second.
>> Beside what Laurent told about using sleep, etc.
>>
>>> first script (the one that does the work)
>>>
>>> trap 'update' HUP
>>> mknod /tmp/dummyfifo p
>>> while true; do
>>>      read < /tmp/dummyfifo > /dev/null 2>&1
>>> done
>>> The problem is that the 'read' generates a
>>> /usr/bin/update: line 1: can't open /tmp/dummyfifo: Interrupted
>>> system call
>> The reason for this is you create your pipe once, but open it
>> again at every iteration of the loop.
>>
>> Try the following:
>>
>> mknod /tmp/dummyfifo p
>> exec 0</tmp/dummyfifo 1>/dev/null 2>&1
>> while true; do
>>     read
>> done
>>
>> This opens the fifo once and assigns it for stdin. After that it
>> stays open until the first script is terminated in any way.
>>
>> In addition stdout *AND* stderr are redirected to /dev/null for
>> all following commands in the script, so you need to redirect to
>> any file or tty when you want do display something.
>
> Thanks!
>
> I like it.  My solution leaves 'cat' processes behind if the script 
> gets killed.  Usually not a problem since it's only invoked at boot.
>
> _______________________________________________
> busybox mailing list
> busybox at busybox.net
> http://lists.busybox.net/mailman/listinfo/busybox



More information about the busybox mailing list