使用C了解共享内存 [英] Understanding Shared Memory Using C

查看:204
本文介绍了使用C了解共享内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using C, I'm trying to set up shared memory. My code looks like:

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进行评估,但显然没有.我应该如何从共享内存中读取?向正确的方向推进将是很棒的.谢谢!

However the second I run that last line, I get a segmentation fault. When debugging, I can print "sharedval" and I get a memory address, presumably the place in memory I got. So I would assume all I have to do is use *sharedval to assess it, but apparently not. How am I supposed to read from the shared memory? A push in the right direction would be wonderful. Thanks!

another.anon.coward的输出:

another.anon.coward's output:

$ ./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检查您的错误消息.使用可以尝试以下代码

The problem in your case could be that there is no associated memory segment for the given key. You need to create a memory segment by passing IPC_CREAT flag in shmget in that case. Please use perror to check your error message. Use can try the following code

    #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了解共享内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆