Q: 程序发生了异常将终止,printf 缓冲区的数据还会刷新吗?
A: 在程序发生异常的时候,操作系统可能会直接结束应用程序,这会导致IO缓冲区的数据不能及时刷新.
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
printf("hello, my cat");
sleep(3);
printf("Byebye, my cat!\n");
return 0;
}
在运行到sleep的时候,按Ctrl + C将使得应用程序直接结束, 这是因为操作系统处理信号(SIGINT)的默认行为是终止应用程序.
Q: 有没有办法在程序异常的时候刷新缓冲区?
A: 可以截获系统异常信号并做恰当操作刷新IO, 比如SIGINT.
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
void sig_int_handler(int sig)
{
printf("Received SIGINT... ");
exit(-1);
}
int main(int argc, char *argv[])
{
signal(SIGINT, sig_int_handler);
printf("hello, my cat... ");
sleep(10);
printf("Byebye, my cat!\n");
return 0;
}
在运行sleep的时候按Ctrl + C:
作者: 陈曦
环境: MacOS 10.14.5
Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.6.0
转载请注明出处