Hi!

I'm trying to use the nanosleep and sleep functions in a program I am trying to write.

I first tried this -

fprintf(stdout,"Hey guys..");
struct timespec t_req, t_rem;
t_req.tv_sec = 1;
t_req.tv_nsec = 500;
if (nanosleep(&t_req, &t_rem) < 0)
   return 0;
fprintf(stdout,"...What's up?");

Since the function nanosleep did not return a negative number, I expected there to be a 1 second (at least) gap between the two outputs.

However, that doesn't seem to be the case. As soon as I run the program, the program waits for 1 second and then throws out all the output.

How can I ensure that the program waits?

Thanks
Kedar

Considering using fflush() to have the output printed immediately

fprintf(stdout,"Hey guys..");
/* force the output onto the screen .. */ 
fflush(stdout);
struct timespec t_req, t_rem;
t_req.tv_sec = 1;
t_req.tv_nsec = 500;
if (nanosleep(&t_req, &t_rem) < 0)
   return 0;
fprintf(stdout,"...What's up?");
commented: Yes +20
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.