c - 尝试附加共享内存的已用地址时出错

标签 c linux unix shared-memory

在第二个参数不为 NULL 的情况下使用 shmget 时收到消息“无效参数”。

它编译没问题,但是在执行时,我得到这个错误信息。

我整天都被困在这个问题上。希望你能帮我! :)

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


int main()
{
    int idSharedMem;
    int *varSharedMem1;
    int *varSharedMem2;

    /* Create the shared memory */
    idSharedMem = shmget((key_t) 0001, sizeof(int), IPC_CREAT | 0666);

    if (idSharedMem == -1)
    {
        perror("shmget");
    }

    /* Allocate a memory address and attached it to a variable */
    varSharedMem1 = shmat(idSharedMem, NULL, 0);

    if (varSharedMem1 == (int *) -1)
    {
        perror("shmat1");
    }

    /* Sign a value to the variable */
    *varSharedMem1 = 5;

    /* Attach an existing allocated memory to another variable */
    varSharedMem2 = shmat(idSharedMem, varSharedMem1, 0);

    if (varSharedMem2 == (int *) -1)
    {
        /* PRINTS "shmat2: Invalid argument" */
        perror("shmat2");
    }

    /* Wanted it to print 5 */
    printf("Recovered value %d\n", *varSharedMem2);

    return(0);
}

最佳答案

使用 shmat(idSharedMem, varSharedMem1, 0); 您尝试在 varSharedMem1 的位置附加段。但是,您之前在该位置附加了一个段,这将导致 EINVAL。 Linux 提供了一个 SHM_REMAP 标志,您可以使用它来替换以前映射的段。

shmat 手册页:

The (Linux-specific) SHM_REMAP flag may be specified in shmflg to indicate that the mapping of the segment should replace any existing mapping in the range starting at shmaddr and continuing for the size of the segment. (Normally an EINVAL error would result if a mapping already exists in this address range.) In this case, shmaddr must not be NULL.

关于c - 尝试附加共享内存的已用地址时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7988064/

相关文章:

c - 客户端浏览器上 C 编译器的虚拟实例

c - C 中的字节交换(字节顺序)

linux - 测量代码性能时的虚拟机或双启动

linux - 启动后如何判断HBase何时就绪?

unix - 我可以获得一个文件与另一个文件的不同程度的百分比吗?

linux - [: <filename>: unexpected error in shell programming

unix - 使用 grep 查找带括号的字符串

c - Mindstorms 的 Robotc **错误** :Undefined variable 'sonarSensor' . 假设为 'short'

linux - 如何更改 Linux 上的文件权限?

Java编译, "No such file or Directory"