Wait/Pause an amount of seconds in C

前端 未结 3 802
温柔的废话
温柔的废话 2021-01-11 12:33

I wrote a little console application, and I want it to pause for a certain number of seconds before the cycle (a while) starts again.

I\'m working on Windows operati

3条回答
  •  有刺的猬
    2021-01-11 12:50

    On Windows, the function to do this is Sleep, which takes the amount of milliseconds you want to sleep. To use Sleep, you need to include windows.h.

    On POSIX-Systems, the function sleep (from unistd.h) accomplishes this:

       unsigned int sleep(unsigned int seconds);
    
       DESCRIPTION
              sleep()  makes  the  calling thread sleep until
              seconds seconds have elapsed or a signal arrives which is not ignored.
    

    If it is interrupted by a signal, the remaining time to sleep is returned. If you use signals, a more robust solution would be:

     unsigned int time_to_sleep = 10; // sleep 10 seconds
     while(time_to_sleep)
         time_to_sleep = sleep(time_to_sleep);
    

    This is of course assuming your signal-handlers only take a negligible amount of time. (Otherwise, this will delay the main program longer than intended)

提交回复
热议问题