【问题标题】:Why wouldn't this doesn't execute the second printf?为什么这不执行第二个 printf?
【发布时间】:2018-11-12 18:36:23
【问题描述】:

所以我的这个伙伴来寻求一些 fork/pipe 的帮助,但他的代码不起作用。
一开始我只是把它归咎于一团糟,但后来我开始阅读更多内容,我开始剥离所有可能是错误的东西,最终得到了这个。

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

typedef void (*tFunction)();

pid_t CreateProcess(tFunction toExecute){
    pid_t pid = fork();
    if(pid)return pid;
    else  {toExecute();exit(0);}
}

void Producer_1(){
    printf("IM PROCESS 1\n");
    printf("Why I no print");
    while(1){}
}
int main(){
    CreateProcess(Producer_1);
    wait(0);
}

输出为:

之后它保持不变,但是这里的 printf 是怎么回事? 如果您在最后一个字符串的末尾放置一个换行符,它会起作用。

【问题讨论】:

    标签: c linux ubuntu gcc posix


    【解决方案1】:

    默认情况下,写入stdout 是行缓冲的。这意味着写入stdout 的文本在写入换行符之前不会被刷新。

    如果您不写换行符,则文本位于缓冲区中。

    【讨论】:

    • 是的,添加fflush(stdout) 以打印文本。
    • 或者最好将换行符添加到第二个打印语句printf("Why I no print\n");
    • @eckenrod 您的解决方案效果如何。据我所知,\n 除了打印换行符之外什么都不做,问题存在是因为程序没有清除缓冲区。那么,您的解决方案是如何起作用的呢?我错过了什么吗?
    • @scipsycho 将换行符打印到行缓冲流会隐式刷新缓冲区。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多