【问题标题】:shm_open() doesn't create shared memory segment ipcsshm_open() 不创建共享内存段 ipcs
【发布时间】:2018-08-09 10:24:06
【问题描述】:

我得到以下成功执行的 C 代码:

...
fd = shm_open(memory_package_name, O_CREAT | O_RDWR | O_EXCL , S_IRUSR | S_IWUSR);

if (fd == -1) { //will fail if file already exists because of flag O_EXCL
    printf("\n shm_open() failed with error [%s]\n",strerror(errno));
    exit(EXIT_FAILURE);
} else {
    printf("shm_open success\n");
}
...

使用ls -l /dev/shm 我看到正确创建了name memory_package_name 的文件,但是当我使用ipcs 时它没有显示任何共享内存段:

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status      

------ Semaphore Arrays --------
key        semid      owner      perms      nsems     

------ Message Queues --------
key        msqid      owner      perms      used-bytes   messages

为什么?

【问题讨论】:

    标签: linux shared-memory ipcs


    【解决方案1】:

    你试过shmget()shmat()吗? 无论如何,如果您需要在两个不相关的进程之间共享内存,您确实需要shm_open(),但我认为您的案例中缺少的一点是使用shmat() 附加到该内存区域的调用。

    【讨论】:

    • 据我了解,shmget()shmat() 已被弃用。我的程序的目标是,由于许可,不应同时允许两个相同的进程。 IE。进程#1 执行,使用shm_open(),重要的是使用标记O_EXCL。然后,如果同一程序的另一个实例作为进程#2 执行,它应该会失败,因为#1 已经在运行。作为旁注,我希望使 shm 不持久,我需要调用 ipcs 以在程序执行后删除 shm,否则每次下一次调用都会失败。
    • 我不知道它们已被弃用,请问您有一些参考资料吗?假设它们不是,我认为在执行shmat() 后,您将在ipcs -m 中看到您的共享内存段。
    • 我的消息来源:here(ctrl + f 已弃用)和here(也 ctrl+f 已弃用)。我会按照您的建议尝试使用shmat,并会回复您。
    • 我在代码中添加了以下几行(shm_open() 之后): ```` int *shm_ptr; shm_ptr = shmat(fd, NULL, 0); if ((int) shm_ptr == -1) { printf("shmat() failed with error[%s]\n", strerror(errno));退出(EXIT_FAILURE); } ```` 结果是输出:````shmat() failed with error[Invalid argument]````` 顺便说一句,我假设我的fd 是从shm_open() 返回的shmid 是否正确?
    • 是的,我也在尝试,但它不起作用。好像我在这里混淆了一些概念,shm_open()shmget()。不好意思,朋友。我将尝试使用mmap(),使用文件描述符fd,请稍等。
    猜你喜欢
    • 1970-01-01
    • 2019-04-05
    • 2013-03-17
    • 2014-03-17
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多