user13695064
user13695064

Reputation:

The sleep function is not functioning as expected

The sleep function here is functioning differently on Windows and Linux.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>

int main()
{
printf("Press 1 to apply for Password Change Request...\n");
                printf("\nPress any other key to try again");
                fflush(stdout);
                for(int j=0; j<2; j++)
                {
                        sleep(1);
                        printf("..");
                }
}
return 0;

On Windows, it is working as it is meant to, waiting for a second then printing .. and then again waiting for a second and then printing ... But on Linux, it is waiting for whole 2 seconds and then printing .... altogether.

What should I do to fix it?

I am using MinGW on Windows.

Upvotes: 1

Views: 73

Answers (1)

Roberto Caboni
Roberto Caboni

Reputation: 7490

Your issue is probably due to the fact that printfs to stdout are buffered, meaning that the data sent through printf is actually printed under certain conditions. The default condition is that data is printed whenever a newline '\n' is sent (line buffering).

According to setvbuf() documentation, three levels of buffering can be set:

  • _IOFBF full buffering
  • _IOLBF line buffering (<-- this is the default value for stdout)
  • _IONBF no buffering

so, calling

 setvbuf(stdout, NULL, _IONBF, 0);

might be a way to solve the issue.

Anyway, the buffer can be flushed asynchronously with fflush():

fflush(stdout);

As an alternative to these solutions, you can simply add a '\n' to your prints

printf("..\n");

or use puts() function:

puts("..");

Upvotes: 2

Related Questions