简体   繁体   English

为什么这样不执行第二个printf呢?

[英]Why wouldn't this doesn't execute the second printf?

So this mate of mine comes asking for help with some fork/pipe stuff, and his code didn't work. 因此,我的这个同伴来寻求有关叉子/烟斗的帮助,他的代码无法正常工作。
Starting off I just attributed to it being a mess, but then I got to reading some more, I started stripping away all the stuff that might have been wrong, ended up with this. 一开始,我只是将原因归结为一团糟,但后来我又读了一些,开始剥离所有可能出错的内容,最后得到了答案。

#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);
}

With as the output: 用作为输出:
在此处输入图片说明
It ofc holds after, but what's up with printf here? 它通常保持不变,但是这里的printf是怎么回事? If you place a newline in the end of the last string, it works. 如果在最后一个字符串的末尾放置换行符,它将起作用。

Writes to stdout are line buffered by default. 默认情况下,写入stdout的行是行缓冲的。 That means that text written to stdout won't be flushed until a newline character is written. 这意味着写入stdout文本在写入换行符之前不会被刷新。

If you don't write a newline, the text sits in the buffer. 如果您不写换行符,则文本将位于缓冲区中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM