Below is an example program employing nanosleep(). If the program receives a signal, then nanosleep() will return before the time has expired (this is according to the API). Thus in the program below I have demonstrated that nanosleep() can be called again after an expected signal has been received/processed.
PHP Code:
#define _POSIX_C_SOURCE 199309
#include <ctime>
#include <cerrno>
#include <csignal>
#include <cstring>
#include <cstdlib>
#include <iostream>
using namespace std;
void sigHandler( int signum )
{
cout << "caught signal " << signum << endl;
}
void sleepFor( time_t seconds, long nsecs )
{
timespec sleepPeriod = { seconds, nsecs };
timespec unusedPeriod;
for (;;)
{
if ( nanosleep( &sleepPeriod, &unusedPeriod ) == 0 )
{
break;
}
else if ( errno == EINTR )
{
cout << "sig detected... resuming timer." << endl;
sleepPeriod = unusedPeriod;
}
else
{
cerr << "Error occurred with nanosleep; reason = " << strerror( errno ) << endl;
break;
}
}
}
int main( int argc, char** argv )
{
time_t seconds = 5;
long nsecs = 0;
if ( argc > 1 )
{
seconds = atoi( argv[1] );
}
if ( argc > 2 )
{
nsecs = atol( argv[2] );
}
signal( SIGUSR2, sigHandler );
sleepFor( seconds, nsecs );
cout << "time up!" << endl;
return 0;
}
P.S. After compiling the program above, run it. While it is running, send a USR2 signal to it to see the program output that the nanosleep (which was interrupted) is being resumed.
Code:
$ g++ nanosleep.cpp -o nanosleep
$ nanosleep 60 &
$ kill -s USR2 `pidof nanosleep`
Bookmarks