printf 缓冲区问题分析 (你想知道的C语言 1.4.1)

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
 
转载请注明出处

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值