简体   繁体   English

fflush()无法正确刷新

[英]fflush() does not flush properly

I'm creating a very simple program execution timer in C. I'll provide sample code below. 我正在用C创建一个非常简单的程序执行计时器。我将在下面提供示例代码。 The problem is that the fflush(NULL) doesn't flush every "Hello World\\n" from the stdout when ending a program with Ctrl + C (ie SIGINT signal). 问题在于,当用Ctrl + C (即SIGINT信号)结束程序时, fflush(NULL)不会从stdout刷新每个"Hello World\\n" They still appear sometimes after the Estimated running time... message and I wonder why. 它们有时仍在“ Estimated running time...消息之后出现,我想知道为什么。

Timer.c 计时器

#include <signal.h>
#include <time.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>

#define _TIMER
#include "timer.h"

static clock_t startTime;

int installTimer(void)
{
    errno = 0;
    if (signal(SIGINT, signalHandler) == SIG_ERR ||
        signal(SIGTERM, signalHandler) == SIG_ERR ||
        signal(SIGABRT, signalHandler) == SIG_ERR)
        return 1;
    if (atexit(displayTimer))
        return 1;
    if ((startTime = clock()) == -1)
        return 1;
    return 0;
}

static void displayTimer()
{
    clock_t endTime;
    if ((endTime = clock()) == -1)
        printf("ERROR: clock() failed.\n");
    else
        printf("Estimated running time: %.4fs\n", (endTime - startTime) / (double) CLOCKS_PER_SEC);
}

static void signalHandler(int signal)
{
    fflush(NULL);
    exit(EXIT_FAILURE);
}

Timer.h: Timer.h:

int installTimer(void);

#ifdef _TIMER
   static void displayTimer(void);
   static void signalHandler(int);
#endif

timerTest.c timerTest.c

#include <stdio.h>
#include "timer.h"

int main(void)
{
    if (installTimer())
    {
        printf("ERROR: installTimer() failed.\n");
        return 1;
    }
    int i;
    for (i = 0; i < 300000; ++i)
        printf("Hello World!\n");
    return 0;
}

Your program invokes undefined behavior. 您的程序调用未定义的行为。 You can't call fflush() inside signal handlers. 您不能在信号处理程序中调用fflush() It is generally a bad idea to call IO library functions inside signal handlers. 在信号处理程序中调用IO库函数通常是个坏主意。

Strictly conforming programs can only call the C standard library functions abort() , _Exit() , quick_exit() , and signal() from within a signal handler. 严格符合标准的程序只能从信号处理程序中调用C标准库函数abort() _Exit()quick_exit()quick_exit()signal()

In other words, fflush() is not asynchronous-safe, so please don't try to do this. 换句话说, fflush()不是异步安全的,因此请不要尝试这样做。

For further details, see this question: I need a list of Async-Signal-Safe Functions from glibc 有关更多详细信息,请参见以下问题: 我需要glibc中的异步信号安全函数列表

That question points to a link with possible workarounds. 该问题指向可能的解决方法的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM