c - fork 和共享内存

标签 c pointers process operating-system fork

<分区>

如果一个进程和它的 fork 有不同的数据副本,那么为什么它们的指针相同?

在下面的示例中,如果计数在父进程和子进程之间共享,我们将看到 count: 2。但是,不共享计数。但是,为什么 &count 在父进程和子进程中返回相同的值?

输出:

count: 1 0x7fff5a617510
count: 1 0x7fff5a617510

程序:

#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>

int main() {
    pid_t pid;
    int count = 0;

    pid = fork();

    count++;
    printf("count: %d %p \n", count, &count);

    return 0;
}

最佳答案

如评论中所述,这是因为虚拟寻址。据我所知,没有办法看到物理地址,因为这是由内核和 MMU 处理的。

另外,请注意即使计数在两个进程之间共享(使用共享内存;例如参见 man shmget),也会出现竞争条件。

关于c - fork 和共享内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17112231/

相关文章:

c++ - 这安全吗? (qt QQueue.dequeue() c++ 内联指针取消引用)

c# - 在进程终止时释放资源

c# - 检测进程的两个窗口

c - 在 C 中将一个 int 值赋给一个指针

c++ - 输出指针的 const 前缀

安卓 M : How to get all processes UID's?

使用前的 C 声明

c - 错误: invalid operands to binary >> (have 'float' and 'int' )

c - 找到字符串 S 中包含字符串 T 的所有字符的最小窗口

c - 自旋锁锁定系统