我正在用 C 创建一个非常简单的程序执行计时器。我将在下面提供示例代码。问题是,当使用+ (即信号)结束程序时,fflush(NULL)
它不会刷新所有内容。它们有时仍然出现在消息之后,我想知道为什么。"Hello World\n"
stdout
CtrlCSIGINT
Estimated running time...
定时器.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);
}
计时器.h:
int installTimer(void);
#ifdef _TIMER
static void displayTimer(void);
static void signalHandler(int);
#endif
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;
}