Jafar - 2016-11-11

A really quick example of implementing a timer via a loadable function based on a requested by Unicon user Michael Meehan (https://sourceforge.net/p/unicon/mailman/message/35484499/)

This is more of a draft, please fee free to use/improve as you see fit and probably contribute back :-)

global count
procedure sigalrm(s)
   count +:= 1   
   write ("fire timer ", count)

end
procedure sigint(s)
stop ("you just pressed ctrl-c")
end

procedure main()

    count := 0
   timer := loadfunc("./time.so", "setTimer")

   #start after 5 seconds, fire the time every seconds 
   timer(5000, 1000)

   trap("SIGALRM", sigalrm)
   trap("SIGINT", sigint)

   write("Press Ctrl+c to exit...")
   repeat {} 
end
///////////////
/// Jafar Al-Gharaibeh
///  Nov-10-2016
///  gcc -std=c99 -shared -fpic -o time.so time.c
///////////////
#include <sys/time.h>
#include "icall.h"
#include <stdio.h>
#include <errno.h>
word
setTimer(int argc, descriptor *argv)
{ 
    struct itimerval value, ovalue, pvalue;
    int which = ITIMER_REAL;
    int mstart, minterval, rc; // milliseconds

    int sstart, sinterval; // seconds

    ArgInteger(1);
    ArgInteger(2);

    mstart = IntegerVal(argv[1]) ;
    minterval = IntegerVal(argv[2]);

    sstart = mstart / 1000;
    sinterval = minterval / 1000;

    mstart = mstart - sstart * 1000;
    minterval = minterval - sinterval * 1000;

    //printf("s:%d i:%d\n", mstart, minterval);

    rc = getitimer( which, &pvalue );
    if (rc){
      fprintf (stderr, "rc1=%d  error:%s\n", rc, strerror(errno));
    }

    value.it_interval.tv_sec = sinterval;
    value.it_interval.tv_usec = minterval * 1000; // convert to micro seconds

    value.it_value.tv_sec = sstart;
    value.it_value.tv_usec = mstart * 1000 ; // convert to micro seconds

    rc = setitimer( which, &value, &ovalue );
    if (rc){
      fprintf (stderr, "rc2=%d  error:%s\n", rc, strerror(errno));
    }

    Return;
}

Sample Run:

Press Ctrl+c to exit...
fire timer 1
fire timer 2
fire timer 3
fire timer 4
fire timer 5
fire timer 6
^Cyou just pressed ctrl-c