工大后院

 找回密码
 加入后院

扫一扫,访问微社区

QQ登录

只需一步,快速开始

搜索
查看: 1609|回复: 5

大家都来说说这两段程序的输出结果是什么

[复制链接]
发表于 2007-7-27 10:23 | 显示全部楼层 |阅读模式
以下代码是基于linux系统的:
#include<sys/types.h>
#include<unistd.h>
main()
{
    pid_t  pid;
    printf("before fork() ");
    pid = fork();

    if(pid<0)
    {
        printf("error  \n");
    }
     else if(pid==0)
    {
        printf("this is child  \n");
    }
    else if(pid>0)
    {
        printf("this is parent!  \n");
    }
}



#include<sys/types.h>
#include<unistd.h>
main()
{
    pid_t  pid;
    printf("before fork()  \n ");   /*请注意这里*/
    pid = fork();

    if(pid<0)
    {
        printf("error  \n");
    }
     else if(pid==0)
    {
        printf("this is child  \n");
    }
    else if(pid>0)
    {
        printf("this is parent!  \n");
    }
}


大家可以分析一下这两段程序输出的结果分别是什么,并且说一下为什么会是这样。
发表于 2007-7-27 13:21 | 显示全部楼层
第一段结果:before fork() this is child
                   before fork() this is parent!
第二段结果:before fork()
                    this is child
                    this is parent!
应该是第一段结果多了个before fork()吧
我只知道,调用fork(),会先返回子进程的PID,再返回创建子进程的父进程的PID
回复

使用道具 举报

发表于 2007-7-27 13:27 | 显示全部楼层
跟踪了一下,发现before fork()在两段代码中都只执行了一次,但却不知为何第一段会多输出了一次,难道是编译器输出的问题?
回复

使用道具 举报

发表于 2007-7-27 14:22 | 显示全部楼层
printf()是line   buffer的,也就是碰到换行时才将当前缓冲输出
回复

使用道具 举报

发表于 2007-7-27 15:52 | 显示全部楼层
学习了。。。
回复

使用道具 举报

 楼主| 发表于 2007-7-28 13:23 | 显示全部楼层
well,一楼和四楼正解。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 加入后院

本版积分规则

QQ|Archiver|手机版|小黑屋|广告业务Q|工大后院 ( 粤ICP备10013660号 )

GMT+8, 2025-5-14 23:47

Powered by Discuz! X3.5

Copyright © 2001-2024 Tencent Cloud.

快速回复 返回顶部 返回列表