Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uwm.edu!linac!midway!clout!chinet!les From: les@chinet.chi.il.us (Leslie Mikesell) Newsgroups: comp.unix.questions Subject: Re: Problem with sleep and signal/alarm. Message-ID: <1991May07.221122.18325@chinet.chi.il.us> Date: 7 May 91 22:11:22 GMT References: <1991May6.153937.28635@msuinfo.cl.msu.edu> Organization: Chinet - Chicago Public Access UNIX Lines: 38 In article <1991May6.153937.28635@msuinfo.cl.msu.edu> winnard@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@chinet.chi.il.us