gpt4 book ai didi

c - 为什么这段代码在使用多进程时不打印两个 "hello"?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:54:34 25 4
gpt4 key购买 nike

我正在学习多进程,知道使用 fork() 时会创建子进程,子进程会获取父进程的堆栈、数据、堆和文本段的副本。

那么为什么下面这段代码不打印两个“hello”呢?

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

static int idata = 111; /* Allocated in data segment */

int main(int argc, char *argv[])
{

int istack = 222; /* Allocated in stack segment */
pid_t childPid;
idata *= 2;
istack *= 2;
printf("hello\n");

switch (childPid = fork()) {
case -1:
printf("fork fail\n");
exit(0);
case 0:
idata *= 3;
istack *= 3;
break;
default:
sleep(3); // Give child a chance to execute
break;
}
/* Both parent and child come here */

printf("PID=%ld %s idata=%d istack=%d\n", (long) getpid(),
(childPid == 0) ? "(child) " : "(parent)", idata, istack);

exit(0);
}

结果是

你好

PID=591(子)idata=666 istack=1332

PID=590(父级)idata=222 istack=444

为什么这段代码不打印两个“hello”?

最佳答案

printf("hello\n"); 发生在 fork() 之前。

当输出是终端时,stdout 默认是行缓冲的,它输出 1 hello 因为 stdout 上刷新>\n.

当输出重定向到文件或管道时,stdout 默认是 block 缓冲的,它输出 2 个 hello,因为父进程和子进程都有hello 缓冲,缓冲区在 exit() 时刷新。

关于c - 为什么这段代码在使用多进程时不打印两个 "hello"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58521377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com