home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / languages / perl / tutorial / eg / itimers.pl < prev    next >
Encoding:
Text File  |  1990-10-29  |  2.2 KB  |  82 lines

  1. #    itimers.pl - timer manipulation functions
  2. #    written by tom christiansen <tchrist@convex.com>
  3. #
  4. #    getitimer, setitimer  - like syscalls but return true on success
  5. #                NB: require packed data for args
  6. #
  7. #    itimer              - conversion function for packing and 
  8. #                unpacking itimers.  packs in scalar context,
  9. #                unpacks in array context.
  10. #
  11. #    alarm              - like libc call but can take and returns floats
  12. #
  13.  
  14. require 'sizeof.ph';
  15. require 'syscall.ph';
  16. require 'sys/time.ph';
  17.  
  18. #
  19. # careful: implementation dependent!
  20. #
  21. $itimer_t = 'L4';  # itimers consist of four longs
  22. $sizeof{'itimer'} = '16' unless defined $sizeof{'itimer'};  # from sizeof.ph?
  23.  
  24. ###########################################################################
  25. # itimer conversion function; this one goes both ways
  26. #
  27. sub itimer {
  28.     if (wantarray) {
  29.     warn "itimer: only expected one arg in array context" if $#_;
  30.     warn "itimer: itimer to unpack not length ".$sizeof{'itimer'} 
  31.         unless length($_[0]) == $sizeof{'itimer'};
  32.     return unpack($itimer_t, $_[0]);
  33.     } else {
  34.     return pack($itimer_t, $_[0], $_[1], $_[2], $_[3]); 
  35.     } 
  36.  
  37.  
  38. ###########################################################################
  39. sub setitimer {
  40.     local($which) = shift;
  41.     local($retval);
  42.  
  43.     die "setitimer: input itimer not length ".$sizeof{'itimer'} 
  44.     unless length($_[0]) == $sizeof{'itimer'};
  45.  
  46.     $_[1] = &itimer(0,0,0,0);
  47.     syscall(&SYS_setitimer, $which, $_[0], $_[1]) != -1;
  48.  
  49. ###########################################################################
  50. sub getitimer {
  51.     local($which) = shift;
  52.  
  53.     $_[0] = &itimer(0,0,0,0);
  54.  
  55.     syscall(&SYS_getitimer, $which, $_[0]) != -1;
  56.  
  57. ###########################################################################
  58. # alarm; send me a SIGALRM in this many seconds (fractions ok)
  59. #
  60. sub alarm {
  61.     local($ticks) = @_;
  62.     local($itimer,$otimer);
  63.     local($isecs, $iusecs, $secs, $usecs);
  64.  
  65.     $secs = int($ticks);
  66.     $usecs = ($ticks - $secs) * 1e6;
  67.  
  68.     $otimer = &itimer(0,0,0,0);
  69.     $itimer = &itimer(0,0,$secs,$usecs);
  70.  
  71.     &setitimer(&ITIMER_REAL, $itimer, $otimer) 
  72.     || warn "alarm: setitimer failed: $!";
  73.  
  74.     ($isecs, $iusecs, $secs, $usecs) = &itimer($otimer);
  75.     return $secs + ($usecs/1e6);
  76.