IPC在C中使用共享内存 [英] IPC using shared memory in C

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

问题描述

嗨朋友



我在c linux中使用共享内存实现IPC。但我的客户端和服务器正在生成不同的地址。为什么这样??或者如何使它们指向相同的内存位置?

我首先执行server.c并在一次迭代后停止,然后是client.c。我得到了不同的地址。



Hi friends

I am implementing IPC using shared memory in c linux. But my client and server are generating different addresses. Why so?? or how to make them point to same memory location?
I am first executing server.c and stopping after one iteration, and then client.c. And I am getting different addresses.

//server.c
#include "/home/user/msgbuf.h"
#define SHMSZ    127
int main()
{
key_t key;
message_buf *m;
char ans='y';
key = 9876;
if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0)
        {
                perror("shmget");
                exit(1);
        }
        printf("\nShared Memory Id = %d\n",shmid);
        if ((m = shmat(shmid, NULL, 0)) == (message_buf *) -1)
        {       perror("shmat");
                exit(1);
        }

      printf("\n m= %d\n",m);
      while(ans=='y')
      {
             sleep(1);
             printf("Enter your choice");
             scanf("%c",&ans);
             getchar();
      }
      return 0;
}







//client.c
#include "/home/user/msgbuf.h"
#define SHMSZ    127
int main()
{
key_t key;
message_buf *rbuf;
key = 9876;
if ((shmid = shmget(key, SHMSZ, 0666)) < 0)
        {
                perror("shmget");
                exit(1);
        }
        printf("\nShared Memory Id = %d\n",shmid);
        if ((rbuf = shmat(shmid, NULL, 0)) == (message_buf *) -1)
        {       perror("shmat");
                exit(1);
        }
      printf("\n rbuf= %d\n",rbuf);
      return 0;
}










//msgbuf.h
typedef struct msgbuf1
{
        int     msglen;
        unsigned char *cp;
}message_buf;





谢谢:)

推荐答案

这是编写共享内存代码的常见挑战。在某些情况下,您可以强制共享内存映射到某个高的未使用的地址。一般来说,这可能不实用或不方便。



由于地址不同,你不能在那里存储指针。相反 - 您可以存储字节偏移量。这对我来说效果很好。



This is the usual challenge in writing shared memory code. In some cases, you can force the shared memory to map to some high, unused address. In general, this may not be practical or convenient.

Since the addresses are different, you can't store pointers there. Instead - you can store byte offsets. That's worked well for me.

//msgbuf.h
typedef struct msgbuf1
{
    size_t msglen;
    size_t offset;
} message_buf;

/* return pointer to the buffer contents in shared memory. */
static char *as_pointer(char *base, message_buf *desc)
{
    return base+desc->offset;
}





这也适用于内存映射文件。



This also works for memory mapped files.


这篇关于IPC在C中使用共享内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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