Reputation: 19
Can anyone show me how to delay or back count in c ? I mean write 1 and 2 after a second. The only way I know is
include<windows.h>
Sleep( 1000 /* milliseconds */ );
can anyone please show me another way to do this? (I have windows 8)
Upvotes: 2
Views: 363
Reputation: 70883
The use of select()
would be another, and also portable solution, although quite unconventional approach to (just) generate a delay.
Upvotes: 0
Reputation: 105876
You can use thrd_sleep
, which is available in C11, and write a simple wrapper for it:
void sleep(time_t seconds){
struct timespec ts, remaining;
timespec_get(&ts, TIME_UTC);
ts.tv_sec += seconds;
while(thrd_sleep(&ts,&remaining) == -1){
timespec_get(&ts, TIME_UTC);
ts.tv_sec += remaining.tv_sec;
}
}
Upvotes: 2
Reputation: 70883
Set an alarm using alarm()
to be fired a second later then call pause()
.
Upvotes: 1
Reputation: 108967
If you're limited to Standard C89
#include <stdio.h>
#include <time.h>
int main(void) {
time_t t;
/* wait until the Standard clock ticks */
t = time(0);
while (time(0) == t) /* void */;
/* print 1 */
puts("1");
/* wait until the Standard clock ticks again */
t = time(0);
while (time(0) == t) /* void */;
/* print 2 */
puts("2");
return 0;
}
If you can use POSIX: use nanosleep().
Upvotes: 2