Problem with sleep and signal/alarm.

Leslie Mikesell les at chinet.chi.il.us
Wed May 8 08:11:22 AEST 1991


In article <1991May6.153937.28635 at msuinfo.cl.msu.edu> winnard at frith.msu.edu () writes:
>I'm having trouble getting the sleep function to work
>under C when I use signal/alarm function.  When the
>signal/alarm call is taken out of the following code, the
>program will print "Sleep 10..." then it will wait 10 seconds
>before printing how long it did not sleep every time through the 
>loop.  But with the signal/alarm function in place the sleep will 
>return immediately and still indicate that it slept 10 seconds
>every time through the loop.
>   ...
>   signal( SIGALRM, SIG_IGN );
>   alarm( 1 );
>
>   while( 1 )
>   {
>      printf("Sleep 10...");
>      x = sleep( (unsigned)10 );

A couple of things:  First, the alarm granularity on unix is 1 second
intervals, so an alarm(1) will go off at the next second transition
after you do it which could be almost instantly.  Second, since sleep()
uses the same alarm signal to wake up, if your alarm goes off it will
reset the signal handler sleep() had installed.

>      if( x == -1 ) perror("");
>      else printf("unslept %d\n", x );
>   }
>}
>
>If you don't know why this is happening maybe you know a way 
>to timeout a read function.  Either solution would be of great help.

No need for the sleep(), just set up the alarm signal handler, do an
alarm(), and then read().  Under SysV, the read() will return with
an error, under BSD you have to longjmp() out of the signal handler.

Les Mikesell
  les at chinet.chi.il.us



More information about the Comp.unix.questions mailing list