免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1668 | 回复: 3
打印 上一主题 下一主题

多进程COW问题求教 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-03-16 16:31 |只看该作者 |倒序浏览
本帖最后由 ppm10103 于 2012-03-16 16:34 编辑


#include "apue.h"
#include "apueerror.h"

//./a.out > temp.out 会产生两次before fork
int glob = 6; /* external variable in initialized data */
char buf[] = "a write to stdout\n";
int main(void) {
    int var; /* automatic variable on the stack */
    pid_t pid;
    var = 88;
    if (write(STDOUT_FILENO, buf, sizeof(buf) - 1) != sizeof(buf) - 1)
        err_sys("write error");
    printf("before fork\n"); /* we don't flush stdout */
    if ((pid = fork()) < 0) {
        err_sys("fork error");
    } else if (pid == 0) { /* child */
        glob++; /* modify variables */
        var++;
    } else {
        sleep(2); /* parent */
    }
    printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var);
    exit(0);
}







为什么
./a.out 只会产生一次 before fork
./a.out > temp.out 会产生两次before fork   

为什么重定向才会有两次呢?

源代码在附件中

sourcecode.rar

2.7 KB, 下载次数: 4

程序源码

论坛徽章:
0
2 [报告]
发表于 2012-03-16 17:10 |只看该作者
The standard I/O library, however, is buffered. Recall from Section 5.12 that standard output is line buffered if it's connected to a terminal device; otherwise, it's fully buffered. When we run the program interactively, we get only a single copy of the printf line, because the standard output buffer is flushed by the newline. But when we redirect standard output to a file, we get two copies of the printf line. In this second case, the printf before the fork is called once, but the line remains in the buffer when fork is called. This buffer is then copied into the child when the parent's data space is copied to the child. Both the parent and the child now have a standard I/O buffer with this line in it. The second printf, right before the exit, just appends its data to the existing buffer. When each process terminates, its copy of the buffer is finally flushed.

论坛徽章:
0
3 [报告]
发表于 2012-03-16 17:11 |只看该作者
ps,lz给出的代码里不是腔调了“/* we don't flush stdout */”嘛。

论坛徽章:
0
4 [报告]
发表于 2012-03-16 17:31 |只看该作者
多谢指点了,就是因为没想明白为什么文本是全缓冲。

现在知道了,块设备是全缓冲。

不同设备的缓冲策略不同
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP