views:

455

answers:

7

I would like to pass a pointer (I am putting a file with data in memory with mmap) to processes spawned using fork + exec, but I am stuck on how to pass a pointer to the exec() spawned process?

UPDATE1:

Thanks for your inputs, I do use shared memory creating it with mmap with MAP_INHERIT flag:

Each mapped file and shared memory region created with the mmap() function is unmapped by a successful call to any of the exec functions, except those regions mapped with the MAP_INHERIT option. Regions mapped with the MAP_INHERIT option remain mapped in the new process image.

source: http://www.uwm.edu/cgi-bin/IMT/wwwman?topic=exec(2)&msection=

UPDATE2:

This is homework excercise, but I think I must stop thinking about pointers and think about the IPC itself. I guess I will go with trying to mmap the same file in child process.

Short code example much appreciated.

Thanks in advance for your help.

A: 

Just pass as text in command-line argument, or in environment variable.

stepancheg
+1  A: 

This can't work. The new process should mmap the file itself as well.

Logan Capaldo
+9  A: 

If you use shared memory, you can't pass the pointer. The pointer will contain the virtual address, which is different from one process to another. You have to exchange offset values, based on the start of the shared memory area.

If you don't use shared memory, you can't exchange pointers of any kind: The other process won't be able to access the memory of your process.

Johannes Schaub - litb
there are way to access non-shared data in other process owned by same user. man ptrace
vitaly.v.ch
+1  A: 

The spawned process should probably open a pipe back to the parent process and ask for the data it needs to map the shared memory segment.

Alternatively you can use boost::interprocess to create a shared memory segment for you and actually pass around the address (it can do the mapping). You're on your own reading that documentation though: http://www.boost.org/doc/libs/1_38_0/doc/html/interprocess.html

jeffamaphone
+2  A: 

To better understand how Processes and Virtual Memory work at Linux.

lsalamon
+1  A: 

Consider passing the offset to the memory within the file to the child process. If the offset is zero, then don't bother, but if you need to pass a 'pointer' to part way through the file, then convert that to an offset from the start address, and pass that to the child. The child can then get to the data by adding the offset to the address it obtains for the mapped file.

Jonathan Leffler
A: 

This is a big area, and you have a lot to choose from.

The key finding those solution is to search for something like Linux inter processor communication or maybe Linux IPC.

A intro into IPC can also be found in books like, Advance Linux Programming (ISBN: 0-7357-1043-0)

Johan