linux - Unix:共享内存。 shm_open() 返回 -1

标签 linux unix posix shared-memory

注意:实际问题在于使用 fork() 函数。所以找到了解决方案。


 //create shared memoery
        int shmfd;
        void *shared_memory = (void *)0;
        shmfd = shm_open("/shm2_rev_to_upp", O_RDWR | O_CREAT | O_EXCL, 0666); //reverse to upper
        if (shmfd == -1) {
           perror("shm_open");
           exit(1);
        }

        if(ftruncate(shmfd, sizeof(struct shared_use_st)) == -1){
          perror("ftruncate");
          exit(1);
        }

        shared_memory = mmap(NULL, sizeof(struct shared_use_st), PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0);

        if(shared_memory == MAP_FAILED){
          perror("mmap");
          exit(1);
        }

    //some code here

    munmap(shared_memory, sizeof(struct shared_use_st));
    shm_unlink("/shm2_rev_to_upp");
    close(shmfd);

我在运行时遇到了这个错误

shm_open: File exists

然后 shm_open() 返回 -1 为什么会这样?!! 请注意,我运行程序的头几次,错误没有出现!!

我该如何解决这个问题?!

最佳答案

手册页解释了各种错误代码:

EEXIST: Both O_CREAT and O_EXCL were specified to shm_open() and the shared memory object specified by name already exists.

关于linux - Unix:共享内存。 shm_open() 返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53094658/

相关文章:

linux - 如何使这个 (l)unix 脚本在 for 循环中动态接受目录名称?

C 耗时 linux

linux - pthread_kill() 在使用 nptl 库时出现段错误

c - Posix 线程在其他线程退出后挂起?

linux - 计数文件,隐藏文件除外

python - 如何在不在命令行指定的情况下专门运行python2.7?

linux - 如何使用shell按字符替换特殊字符

c++ - 进程 fork 后 RAII 对象会发生什么?

r - Windows 上 RStudio 中的波浪号扩展

c++ - 极其简单的 POSIX C++ IPC