c - 在 c system() 之前执行 printf() 即使 printf 先出现

标签 c linux gcc

<分区>

我刚开始使用 c 中的 system() 函数,我想使用 system 函数从内部启动同一个可执行文件,所以我编写了以下程序

#include <stdlib.h>
#include <stdio.h>

int main()
{
    printf("some string");
    system("./a.out");
}

-我是用gcc编译的-

当我运行程序时它没有打印任何东西,它一直运行直到我使用快捷键 ctrl-c 停止执行,然后它开始打印输出(直到我停止它才打印任何东西)

我认为这些语句应该按顺序执行,为什么直到我停止它才打印出任何东西?

最佳答案

默认情况下,当 stdout 连接到终端时,它是行缓冲的。

printf("some string");

里面没有 '\n' 并且你也没有在它之后调用 fflush(stdout);,所以所有这些 printf ("some string"); 所做的是将 "some string" 复制到您的 stdout 的输出缓冲区中。

缓冲区在 main 结束时被刷新。

printf("some string\n"); 将立即刷新缓冲区,前提是 stdout 连接到终端并且您没有更改 stdout 的缓冲。

printf("一些字符串"); fflush(stdout); 将立即刷新缓冲区,无论上下文如何,也不需要 '\n'

关于c - 在 c system() 之前执行 printf() 即使 printf 先出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55301280/

相关文章:

c - Rand() 在 C 中不是唯一的

c - 基于Web的C语言开发

linux - 更改目录中的文件名

c++ - 通用成员函数定义,可从 'const' 和 'non-const' 对象实例化

无法命名具有指定优化的可执行文件

gcc - 在 gcc 中使用自旋锁

c - 用C打开文件时出现段错误

c - 如何更改通过引用传递给函数的字符串的值?

c - 在 32 位 Debian Squeeze 下编译的 C 程序导致我 friend 的 64 位程序出现段错误

linux - linux 服务器的 tcl 中不同数量的变量名和字段说明符错误