简体   繁体   中英

how can i make my program sleep for some amount of time?

I want to put my program in sleep for some desired time. but i also want that if enter is pressed then program wakes up.

clock_t t;
int sleep_time=10;
t=clock();
while(1){
int temp=clock()-t;
double time_now=(double)(temp)/CLOCKS_PER_SEC;
    if(time_now>=sleep_time){
       break;
    }
    if(getchar()=='\n'){
       break;
    }

}

but this program will wait for input and if input is not given it will not break How can i do this.

On a POSIX platform, you can use select() / poll() on standard input and with a timeout parameter:

#include <sys/select.h>
#include <unistd.h>
int main(void)
{
    fd_set inp; FD_ZERO(&inp); FD_SET(STDIN_FILENO,&inp);
    select(1,&inp,0,0,&(struct timeval){.tv_sec=1});
}

With signal handlers on you'll also need to watch out for EINTR and redo the request with the remaining time.

Unfortunately, you cannot count on either select() or poll() to give you the remaining time ( select can and will on Linux, through the struct timeval* parameter, but the behavior isn't portable), so you'll need to use clock_gettime to calculate it yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM