You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何混用write与printf函数会出现代码执行顺序异常?

为什么混用write和printf会出现输出顺序颠倒?

你的代码如下:

#include <stdio.h>
#include <unistd.h>
main()
{
    printf("ca");
    write(1, "lu", 2);
}

运行结果:

$ gcc bar.c 2>/dev/null && ./a.out
luca$ 

核心原因:缓冲机制的差异

  • printf是C标准库提供的带缓冲的I/O函数:标准输出(stdout)默认是行缓冲模式——只有当输出内容包含换行符\n、缓冲区被填满,或者程序退出时,才会把缓冲区里的内容刷到内核,最终输出到终端。你的代码里printf("ca")没有换行符,所以"ca"会暂时存在用户态的缓冲区里,不会立刻输出。
  • write是系统调用:它直接绕过用户态缓冲,把数据写入内核的文件描述符缓冲区,随后就会输出到终端。

所以程序执行时,write先把"lu"输出,等到程序结束时,printf的缓冲区才被刷新,输出"ca",最终就出现了luca的结果。

验证与解决方法

如果想让printf的内容立刻输出,可以手动刷新缓冲区:

#include <stdio.h>
#include <unistd.h>
main()
{
    printf("ca");
    fflush(stdout); // 手动刷新标准输出缓冲区
    write(1, "lu", 2);
}

运行后会得到预期的calu。

或者给printf的内容加上换行符,触发行缓冲的自动刷新:

#include <stdio.h>
#include <unistd.h>
main()
{
    printf("ca\n");
    write(1, "lu", 2);
}

运行结果会是:

ca
lu$

内容的提问来源于stack exchange,提问作者luca112358

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 19:15:50