开发者

Allocate object in shared memory

It might be a silly question but... I have two processes P1 and P2. Can P1 allocate easily an object O in a shared memory that would be seen for P2? (P1 passes to P2 a pointer to O using a pipe). Something like:

// P1
ptr1 = new SharedMem开发者_运维知识库oryObject(); // object O
pipe.send(ptr1)

// P2
ptr = pipe.recieve()
// I have access to O now

I want to avoid serializing and piping the objects, I would like to create them in shared memory and pass pointers


Each process has its own address space which means that although a physical memory address may be shared between the two processes, this probably will correspond to different addresses in each process's address space. This means that when designing object that will exist in shared memory you MUST ensure they use offsets or indexes and not pure pointers.

Sharing memory will create synchronisation issues which can cause no end of problems, so unless you really have to, I will advise you to use the pipe route in preference to shared memory.


No. A pointer from P1 is meaningless to P2.

However, you might want to read about "based pointers", which work better for inter-process communications.

As a side-effect, any class that uses normal pointers internally (instead of based pointers) can't be shared this way.


This answer is specifically for linux

You can use shm_open function to create or open a shared memory file, which can be mmap()-ed. As you can see from man pages for mmap:

The actual place where the object is mapped is returned by mmap()

and

On success, mmap() returns a pointer to the mapped area. On error, the value MAP_FAILED (that is, (void *) -1) is returned, and errno is set appropriately.

Therefore, you can not pass the pointer from one process to another. However, you can pass the shared memory name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜