Chinaunix首页 | 论坛 | 博客
  • 博客访问: 58843
  • 博文数量: 16
  • 博客积分: 318
  • 博客等级: 一等列兵
  • 技术积分: 131
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-02 10:43
文章分类

全部博文(16)

文章存档

2011年(16)

我的朋友

分类: C/C++

2011-03-04 12:07:25

fork()后的代码会被执行两次,一次是父进程,一个产子进程,两个进程的变量地址空间是相互独立的,子进程复制一份父进程的变量映像。

#include

#include

#include

int main(void)

{

        pid_t childpid;

        int x=0;

        childpid = fork();

 

        if(childpid == -1)

                {

                        perror("Failed to fork");

                        return 1;

                }

        if(childpid==0)

                        {

                        x=1;  /*在这里重新设置x的值不会影响父进程里x的值

                        printf("I am child %ld and x is%d \n",(long)getpid(),x);

 

                        }

        else

                        printf("I am parent %ld and x is %d\n",(long)getpid(),x);

        return 0;

 

}

 

执行结果

[root@localhost code]# ./t_fork2
I am child 10933 and x is1
I am parent 10932 and x is 0

阅读(1375) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~