睡眠功能未按预期运行

The sleep function is not functioning as expected

此处的睡眠功能在 Windows 和 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;

Windows 上,它正在按预期工作,等待一秒钟然后打印 .. 然后再次等待一秒钟和然后打印 ..。 但是在 Linux 上,它等待整整 2 秒,然后一共打印 ....

我应该怎么做才能解决它?

我在 Windows 上使用 MinGW

你的问题可能是因为 printfs 到 stdout 被缓冲了,这意味着通过 printf 发送的数据实际上打印在一定条件下。默认条件是每当发送换行符 '\n' 时打印数据(行缓冲)。

根据setvbuf()文档,可以设置三个级别的缓冲:

  • _IOFBF 全缓冲
  • _IOLBF 行缓冲 (<-- 这是标准输出的默认值)
  • _IONBF 无缓冲

所以,调用

 setvbuf(stdout, NULL, _IONBF, 0);

可能是解决问题的方法。

无论如何,可以使用 fflush():

异步刷新缓冲区
fflush(stdout);

作为这些解决方案的替代方案,您可以简单地在打印件中添加 '\n'

printf("..\n");

或使用puts()函数:

puts("..");