0

I was writing a simple C program, then I ran to a problem: when I put nanosleep() in a loop, my output is different from what I expect. The code is simple:

struct timespec ts = {1, 0};
    for(int i = 0; i<4; i++)
    {
      printf("test ");
      nanosleep(&ts,NULL);
    }

From what I understand, it should print word "test", then wait 1 second, repeat. However, when I run it, it waits for 4 seconds, and then it prints "test" four times, immediately. What confuses me the most, is that the printing of each word should be done before sleeping, but it seems like it doesn't happen even in the first iteration of the loop. I realize that it may not be correct use of nanosleep() but in man nanosleep I couldn't find anything about not using it in loops.

0 Answers0