I want to write a program in C that performs some function and then sleeps for some minutes. During this sleep period I would like to do something and exit if a key is pressed.
int main()
{
while(1)
{
/*body*/
sleep(300);
}
/*some lines here*/
return 0;
}
Is there anyway that I can exit the loop during either the sleep period or at any time using a non-blocking key listener?
Just don't sleep for 300 seconds but rather 300 x for 1 second and check for key press:
int main()
{
while(1)
{
/*body*/
for ( int i=0; i<300; i++ )
{
if (keypressed())
doSomething();
}
}
/*some lines here*/
return 0;
}
EDIT: Why the while (1)
in your code? Do you really want to run your program endlessly? (In that case, /*some lines here*/
doesn't make sense.)