c++ - 将共享内存指针类型转换为整数指针

标签 c++ linux ubuntu shared-memory

int main()
{
    key_t key = ftok("yu", 65);
    int shmid = shmget(key, 100 * sizeof(int), 0666 | IPC_CREAT);
    int** Matr = (int**)shmat(shmid, (void*)0, 0);

    for (int i = 0; i<3; i++)
    {
        for (int j = 0; j<3; j++)
        {
            Matr[i][j] = i + j; // writing to shared memory
        }
    }

    shmdt(Matr);
    return 0;
}
我正在尝试将共享内存指针类型转换为整数双指针但是每次我编译代码时,它都会说段错误(核心转储)。有人可以告诉我该怎么做吗?提前致谢。
P.S:我在 C++ 上做这个。

最佳答案

你可以试试下面的代码。
主要区别在于矩阵是用一维连续内存块(数组)实现的,因此 Matrint* 类型.
通过从 2 个矩阵索引 (idx) 计算数组 (i,j) 中的索引来“手动”管理矩阵的 2D 索引。
注:我建议您为所有系统调用添加错误处理。

#include <sys/ipc.h>
#include <sys/shm.h>

int main()
{
    key_t key = ftok("yu", 65);
    // check if key is -1 and if so handle the error ...
    int shmid = shmget(key, 100 * sizeof(int), 0666 | IPC_CREAT);
    // check if shmid is -1 and if so handle the error ...
    int* Matr = (int*)shmat(shmid, (void*)0, 0);
    // check if Matr is (void*)-1 and if so handle the error ...

    int width = 3;
    int height = 3;
    // NOTE: width * height must be <= 100 (according to the declared size of the shared memory).

    for (int j = 0; j<height; ++j)
    {
        for (int i = 0; i<width; ++i)
        {
            int idx = j * width + i;
            Matr[idx] = i + j; // writing to shared memory
        }
    }

    int st = shmdt(Matr);
    // check if st is -1 and if so handle the error ...
    return 0;
}

关于c++ - 将共享内存指针类型转换为整数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72499552/

相关文章:

c++ - 从常量成员函数返回迭代器

php - 同时执行多个PHP脚本

apache - 在 Apache Web Server 前配置 NGINX Reverse Proxy

c++ - 非常大的数组——C 数组与 C++ 数组。 Visual Studio - 超过最大值 (268435456)

c++ - 在C++程序中删除全局变量

Linux 内核解压缩 Linux 消息未在 UART 上打印

c - 某些对 "calloc"的调用速度快得令人怀疑

bash - Ubuntu使用脚本将JAVA_HOME路径添加到bashrc不起作用

java - 我在 ubuntu 18.4 中安装 tomcat 时遇到问题

c++ - C++继承中,派生类如何禁用基类的某些元素(数据或函数)?