Quote:
Originally Posted by nagaraju1024
my doubt is which part of process address space it will attach?
|
A good question. The man pages make it somewhat clear, but not completely so.
If you take the newer POSIX path (which you should probably do if you're running Linux), use
shm_open() to get a file descriptor for the shared memory. The first process to do so should use the
O_CREAT flag; in fact, all of the processes may do so. All the processes involved should use the same
name argument, so they'll get the same shared segment. Then use
mmap() to get the address of that memory, in terms of your program's address space.
If you want, you can use
munmap() and
close() when your process is done using the segment, but I believe this is done automatically when the process exits. The final process should use
shm_unlink() to delete the segment. If this works the same as the older, pre-POSIX way (which I'll describe in a moment), there's a limited number of these shared memory segments available in the system. If you don't unlink each one when you're competely done with it, you'll eventually run out, and you won't be able to use shared memory again until you reboot the system.
I'm not sure, but I believe that
every process which uses a particular piece of shared memory can
shm_unlink() it, as long as all processes which want to use it have already
shm_open()ed it. It may even be the case that each such process can do so before being done with that shared memory, thus making sure it gets deleted when there is no longer need for it. Experiment with this to be sure.
The pre-POSIX way, which is useful for older systems, is to use
shmget(), in which the numerical
key takes the place of the string
name in
shm_open. Then
shmat() is used (instead of
mmap(). Instead of using
munmap(), use
shmdt(). Instead of using
munmap() and
close(), use
shmdt(). To delete the shared memory segment, use
shmctl() with the
IPC_RMID command. This can be done by any one process (or all of them if you wish, possibly making your design simpler) as soon as every process which uses this shared memory has
shmat()ed it.
Hope this helps.