如何将变量放入共享内存? [英] How to put a variable in a shared memory?

查看:83
本文介绍了如何将变量放入共享内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带值的变量,我想与进程共享它.

I have a variable with a value and I want to share it with the proccesses.

例如:

typedef struct {
  unsigned int a;
  unsigned int b;
  another_struct * c;
} struct1;
...
struct1 A ={...};
...

现在,我想创建一个共享内存区域并将 A 变量放在该区域中.我该怎么做?

Now, I want to create a shared memory region and put the A variable in this region. How can i do this?

推荐答案

共享内存是一个操作系统 功能(在 C11 中不存在).它不是提供"的符合 C 标准.

Shared memory is an operating system feature (which does not exist in C11). It is not "provided" by the C standard.

我猜您正在为 Linux 编码.顺便说一句,阅读高级 Linux 编程.

I guess that you are coding for Linux. BTW, read Advanced Linux Programming.

首先阅读shm_overview(7).您需要同步,所以也请阅读 sem_overview(7).

Read first shm_overview(7). You'll need to synchronize, so read also sem_overview(7).

您将获得一些共享内存段到一个指针中,然后您将使用该指针.

You'll get some shared memory segment into a pointer and you'll use that pointer.

首先用shm_open(3)<打开共享内存段/a>:

First, open the shared memory segment with shm_open(3):

int shfd = shm_open("/somesharedmemname", O_RDWR|O_CREAT, 0750);
if (shfd<0) { perror("shm_open"); exit(EXIT_FAILURE); };

然后在那个mmap(2)上使用<代码>shfd:

void* ad = mmap(NULL, sizeof(struct1), PROT_READ|PROT_WRITE, MAP_SHARED, 
                shfd, (off_t)0);
if (ad==MAP_FAILED) { perror("mmap"); exit(EXIT_FAILURE); };

然后您可以将该地址转换为指针:

Then you can cast that address into a pointer:

struct1* ptr = (struct1*)ad;

并使用它.(不要忘记关闭).

and use it. (Don't forget to close).

顺便说一句,你不能并且你不能把一个变量放入共享内存.您会获得一个指向该共享内存的指针并使用它,例如ptr->a = 23;

BTW, you don't and you cannot put a variable into a shared memory. You get a pointer to that shared memory and you use it, e.g. ptr->a = 23;

当然,不要期望相同的共享段被映射到相同的地址(所以你不能轻松处理像c这样的指针字段)不同的过程.您可能应该避免共享 struct-s 中的指针字段.

Of course, don't expect the same shared segment to be mapped at the same address (so you can't easily deal with pointer fields like c) in different processes. You probably should avoid pointer fields in shared struct-s.

请注意,C 变量仅在编译时存在.在运行时,您只有位置和指针.

Notice that C variables exist only at compile time. At runtime, you only have locations and pointers.

附注.共享内存是一种非常困难的进程间通信机制.您或许应该更喜欢 pipe(7)-s 或 fifo(7)-s 并且您需要多路复用使用 poll(2).

PS. Shared memory is a quite difficult inter-process communication mechanism. You should perhaps prefer pipe(7)-s or fifo(7)-s and you'll need to multiplex using poll(2).

这篇关于如何将变量放入共享内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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