gpt4 book ai didi

c - C 中的 SIGINT 是否会自动刷新和关闭打开的流?

转载 作者:太空狗 更新时间:2023-10-29 15:14:33 28 4
gpt4 key购买 nike

我在手册页中读到,当调用 exit() 时,所有流都会自动刷新和关闭。起初我对这是如何完成的以及它是否真正可靠表示怀疑,但看到我无法再找到更多我将接受它只是有效 - 我们会看看是否有任何东西爆炸。无论如何,如果这种流关闭行为出现在 exit() 中,这种行为是否也出现在 SIGINT 的默认处理程序中(中断信号通常用 Ctrl+C 触发)?或者,是否有必要做这样的事情:

#include <signal.h>
#include <stdlib.h>

void onInterrupt(int dummy) { exit(0); }

int main() {
signal(SIGINT, onInterrupt);
FILE *file = fopen("file", "a");
for (;;) { fprintf(file, "bleh"); } }

要正确关闭文件?或者可以安全地省略 signal(SIG...void onInterrupt(... 行吗?

请限制对 C、C99 和 POSIX 的任何回复,因为我没有使用 GNU libc。谢谢。

最佳答案

C99 规范 7.19.3 的保证较弱:

5 If the main function returns to its original caller, or if the exit function is called, all open files are closed (hence all output streams are flushed) before program termination. Other paths to program termination, such as calling the abort function, need not close all files properly.

4 A file may be disassociated from a controlling stream by closing the file. Output streams are flushed (any unwritten buffer contents are transmitted to the host environment) before the stream is disassociated from the file.

所以在 C99 中,如果它被关闭就会被刷新。

POSIX exit function有更多细节,特别是 _exit 是否关闭流是实现定义的。

关于c - C 中的 SIGINT 是否会自动刷新和关闭打开的流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2044368/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com