每当在fork()之前调用printf()时,每次调用fork()时,printf()的循环输出都会输出到stdout。为什么'\ n'可以解决这个问题?

唐·福马雷

当我在玩耍时,fork()我注意到了一个相当奇怪的行为,但是我不知道为什么会这样。

在下面的示例中,每次调用之前将fork()调用的输出printf()打印到stdout。test输出中的值表明printf()不会真正再次执行,否则test每次都会增加

甚至陌生人-或可能是解决方案的关键-的事实是,当我添加\n到printf()的格式字符串的末尾时,不会发生此行为

有人知道为什么会这样吗?也许与stdout缓冲区有关?我对这些东西不是很熟悉。

还是我做错了什么?

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main(char* args) {
    pid_t pid;
    int wstatus;
    int test = 0;

    printf("\n[%d] parent start | test = %d ", getpid(), test++);

    // This works fine
    //printf("\n[%d] parent start | test = %d \n", getpid(), test++);

    for(int i = 0; i < 5; i++) {
        if((pid = fork()) == 0) {
            //printf("\n[%d] Child spawned ", getpid());
            exit(0);
        }
        //printf("\n[%d] Printing with fork() commented out works fine", getpid());
    }

    while(wait(&wstatus) > 0);

    printf("\n[%d] parent end\n\n", getpid());
    return 0;
}

输出:

[342470] parent start | test = 0 [342470] parent start | test = 0 [342470] parent start | test = 0 [342470] parent start | test = 0 [342470] parent start | test = 0 [342470] parent start | test = 0 
[342470] parent end

万一有什么用

$ uname -a
Linux Aspire 5.4.0-26-generic #30-Ubuntu SMP Mon Apr 20 16:58:30 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
托马斯·迪基

printf写文本到标准输出缓冲器,其被最终写入经由叉的每个分支exit呼叫。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章