在分叉的进程上使用相同的变量 [英] Using same variable on forked processes

查看:50
本文介绍了在分叉的进程上使用相同的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这个代码

void func(int* count)
{
    *count += 1;

    char* buf[100];
    sprintf(buf, "%d -> %d\n", count, *count);
            write(1, buf, strlen(buf));
}
int main()
{
    int* count = 0;
    int pid = fork();
    if(pid == 0)
    {
        func(&count);
    }
    else
    {
        func(&count);
    }

    return 0;
}

将打印

1444711088 -> 1
1444711088 -> 2

因为2个fork使用相同的存储单元(1444711088)作为 count 变量,并且其中之一修改了它的值时,另一个将受到影响.但是它没有按预期工作.它正在打印:

because 2 fork using same memory cell (1444711088) for count variable and when one of them modify the value of it, other one will be affected. But it's not working as expected. It's printing this :

1444711088 -> 1
1444711088 -> 1

您能告诉我这段代码在哪里吗?

Can you tell where is the problem with this code ?

推荐答案

您问过:

您能告诉我这段代码在哪里吗?

Can you tell where is the problem with this code ?

代码有问题,但不是您认为的问题所在.您对分叉过程如何工作的理解不太正确.

There is a problem with the code but not where you think it is. Your understanding of how forked processes work is not quite right.

每个进程都有自己的进程内存空间副本.父进程的地址 1444711088 与子进程的地址 1444711088 不同.它们可以容纳独立变化的值.

Each process gets its own copy of the process memory space. The address 1444711088 of the parent process is different from the address 1444711088 of the child process. They can hold values that vary independently.

您的代码有未定义的行为.

Your code is subject to undefined behavior.

int* count = 0;

这将初始化指向 0 的指针,该指针不是有效地址.您是否打算使用:

That initializes the pointer to 0, which is not a valid address. Did you mean to use:

int count = 0;

相反?

这篇关于在分叉的进程上使用相同的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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