user1018513
user1018513

Reputation: 1682

Sharing memory across an exec call

I know that execve discards any exiting dynamically allocated memory. My job would be to have a C program which calls a binary and then communicates with it using a shared buffer. The key here is efficiency as the buffer is of a relatively small size, so I want to avoid rpc/the use of syscalls (such as shmat, etc) as much as possible.

Previously, i'd been creating the buffer in a C program then using clone (with the CLONE_VM flag set) followed by an exec call to the binary. Obviously this didn't work as exec replaces the image.

I'm not worried about how efficient set up is, my goal is to have the most efficient communication system once that has been set up.

Unless anyone has a way to execute a binary within the same address space so that they can share malloced areas of memory, I am going to use shmget and shmat (attaching the shared memory from within the executed binary).

Is there a more efficent way to achieve shared memory?

Upvotes: 0

Views: 1683

Answers (1)

jxh
jxh

Reputation: 70472

The problem statement in your question is not well formed. Since shmat will only be called once per exec, it's cost is amortized across the lifetime of the process. Since in your comments you state you have to exec a different program (it is unclear why), threads are out.

You are afraid that using shared memory associated with shmat to pass a message incurs a greater penalty than some memory shared via some other means. This fear is largely unfounded. You would use the shared memory just like any other dynamically allocated memory, with the caveat that the address offset may be different for each process attached to it.

You do not explicitly state your requirements or the parameters of the problem, but in your comments you state you want to pass a message between two processes without incurring a context switch. This is possible by having the consumer spin wait if the message queue is empty. However, this is only fruitful if the consumer and producer are running on different processors.

In anycase, I would consider all these issues late stage optimizations. Focus first on correctly delivering the messages. Then find out where the bottlenecks are if the performance is not at an acceptable level.

Upvotes: 2

Related Questions