Display something every 3 seconds

I can’t figure out how to display something (like hello world) every 3 seconds. I only write C programming with the gcc compiler in linux. We can stop it with Ctrl + c. I just want the simplest and easiest way to manipulate this code with my project.

Thank you so much in advance!

+3
source share
6 answers

You may have a problem in the fact that standard output is usually buffered, which means that the implementation expands the output until it is convenient to write it. If you write every three seconds (and sleep(3)is a good way to do this) and it does not appear every three seconds, try inserting fflush(stdout);or writing to the standard error output using `fprintf (stderr," something \ n ");

+6
source
while(1) {
    printf("something\n");
    sleep(3);
}
+9
source
sleep(3);

sleep X . , , 3 , . , usleep, u , . . .

+4

, (while (1) { ... }) .

, sleep . sleep, , nanosleep, .

#include <stdio.h>
#include <time.h>

int main()
{
  struct timespec t = { 3/*seconds*/, 0/*nanoseconds*/};
  while (1){
    printf("Wait three seconds and...\n");
    nanosleep(&t,NULL);
    fflush(stdout); //see below
  }
}

: (\n) outpu, , , , , ( , ). fflush.

+1

, , , - - , n , /usr/bin/watch. .

+1

setvbuf(). , , , (stdout) (stderr).

#include <stdio.h>

int main(int argc, char* argv[]) {
    setvbuf(stdout, NULL, _IONBF, 0);
    while ( 1 ) {
        printf("Wait 3 seconds... ");
        sleep(3);
    }
}

, \n printf. setvbuf(), , ( 1024 ).

0
source

Source: https://habr.com/ru/post/1727267/


All Articles