ç叉处理全局变量 [英] C fork dealing with global variable

查看:109
本文介绍了ç叉处理全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不理解这个程序的输出:

I'm not understanding the output of this program:

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

int i = 0;

int main()
{
    while(i<3)
    {
        fork();

        printf("%d\n",i);
        ++i;
    }
}

输出是:

0
1
2
2
1
2
0
1
2
2
2
1
2
2

可以请别人告诉我,我应该如何才能解决这一问题,充分理解为什么我得到这个输出?

Can please someone tell me how I should tackle this issue in order to fully understand why I'm getting this output?

推荐答案

叉将使过程的副本。过程中的一个独立的副本。所以,如果一个全局变量包含3个的时候你叉,这个过程的每个副本得到他们自己3.如果他们修改,其修改是完全独立的。

Fork will make a copy of the process. An independent copy of the process. So, if a global variable contains 3 at the time you fork, each copy of the process gets their very own 3. And if they modify, their modifications are completely independent.

这篇关于ç叉处理全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆