gpt4 book ai didi

c - 使用 C 理解共享内存

转载 作者:太空狗 更新时间:2023-10-29 11:26:33 25 4
gpt4 key购买 nike

使用 C,我正在尝试设置共享内存。我的代码如下所示:

key_t key = ftok("SomeString", 1);
static int *sharedval;
int shmid = shmget(key, sizeof(int), S_IRUSR | S_IWUSR); // less permissions
sharedval = (int *) shmat(shmid, NULL, 0);
*sharedval = 0;

然而,当我运行最后一行时,出现了段错误。调试时,我可以打印“sharedval”并得到一个内存地址,大概是我得到的内存中的位置。所以我假设我所要做的就是使用 *sharedval 来评估它,但显然不是。我应该如何从共享内存中读取?朝着正确的方向插入将是美妙的。谢谢!

编辑:

another.anon.coward 的输出:

$ ./a.out 
ftok: No such file or directory
shmget: No such file or directory
Trying shmget with IPC_CREAT
shmget success
shmat success
Segmentation fault: 11

最佳答案

您的问题可能是给定键没有关联的内存段。在这种情况下,您需要通过在 shmget 中传递 IPC_CREAT 标志来创建内存段。请使用 perror 检查您的错误信息。使用可以试试下面的代码

    #include <stdio.h> //For perror
...

key_t key = ftok("SomeString", 1);
if ( 0 > key )
{
perror("ftok"); /*Displays the error message*/
/*Error handling. Return with some error code*/
}
else /* This is not needed, just for success message*/
{
printf("ftok success\n");
}

static int *sharedval;
int shmid = shmget(key, sizeof(int), S_IRUSR | S_IWUSR | IPC_CREAT);
if ( 0 > shmid )
{
perror("shmget"); /*Displays the error message*/
}
else /* This is not needed, just for success message*/
{
printf("shmget success\n");
}

sharedval = (int *) shmat(shmid, NULL, 0);
if ( 0 > sharedval )
{
perror("shmat"); /*Displays the error message*/
/*Error handling. Return with some error code*/
}
else /* This is not needed, just for success message*/
{
printf("shmat success\n");
}
*sharedval = 0;
...

关于c - 使用 C 理解共享内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7495326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com