【问题标题】:C fork is a copy of parent when using printf [duplicate]使用 printf 时,C fork 是父级的副本 [重复]
【发布时间】:2017-09-12 09:47:27
【问题描述】:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(void) {
    write(STDOUT_FILENO,"1",1);
    if(fork() > 0) {
        write(STDOUT_FILENO,"2",1);
        write(STDOUT_FILENO,"3",1);
    }
    else {
        write(STDOUT_FILENO,"4",1);
        write(STDOUT_FILENO,"5",1);
    }
    write(STDOUT_FILENO,"\n",1);
    return 0;
}

输出为1 2 3 \n 4 5 \n

为什么如果我替换 printf(最后没有换行符)的所有写入函数,例如 write(STDOUT_FILENO,"1",1)==printf("1"),我得到 1 2 3 \n 1 4 5 \n,就像孩子正在复制叉子上方的行一样?

【问题讨论】:

    标签: c printf fork parent


    【解决方案1】:

    是的,这是因为标准输出流被缓冲,直到它遇到这个帖子Why does printf not flush after the call unless a newline is in the format string? 的结束行。因此,当您形成一个新进程时,这个缓冲区会被复制到子进程的标准输出缓冲区,因为我们实际上是在为子进程创建一个新的内存空间。 (其实不完全,见Specifically, how does fork() handle dynamically allocated memory from malloc() in Linux?

    这是可行的

    #include <stdio.h>
    #include <sys/types.h>
    #include <unistd.h>
    int main(void) {
    
    printf("1");
    fflush(stdout);
    if(fork() > 0) {
            printf("2");
            printf("3");
    } else {
            printf("4");
            printf("5");
    
    }
    printf("\n");
    return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-07-01
      • 2020-05-08
      • 1970-01-01
      • 2013-01-16
      • 2015-11-14
      • 2015-12-26
      • 1970-01-01
      • 2021-04-19
      • 2015-03-25
      相关资源
      最近更新 更多