Path: utzoo!censor!geac!torsqnt!news-server.csri.toronto.edu!cs.utexas.edu!sun-barr!newstop!sun!amdcad!dgcad!dg-rtp!hunt From: hunt@dg-rtp.rtp.dg.com (Greg Hunt) Newsgroups: comp.unix.questions Subject: Re: Shared memory and malloc Message-ID: <1990Dec19.144959.16561@dg-rtp.dg.com> Date: 19 Dec 90 14:49:59 GMT References: <647@voodoo.UUCP> Sender: usenet@dg-rtp.dg.com (Usenet Administration) Reply-To: hunt@dg-rtp.rtp.dg.com Organization: Data General Corp., Research Triangle Park, NC Lines: 47 In article <647@voodoo.UUCP>, howie@voodoo.voodoo.uucp (howie) writes: > > Here's a question for someone with experience with shared memory (and > malloc). > > I have a pointer in a segment, shared by two processes. If one of the > processes does a malloc() using that pointer, will the other process have > access to that portion of memory that has been malloced. No, I'm afraid not. The malloc() call allocates unshared space from the calling process's stack or heap. That memory can only be used by the calling process itself, the other processes cannot see that memory since it's not in their process. To do what you want, you have to set aside a portion of the shared memory segment that both processes share as a shared "heap", and write your own routines to parcel out that shared memory. This means you need to write your own versions of malloc() and free() that operate on shared memory (call them something else to avoid interfering with the standard malloc() and free()). If that sounds too complex to you, I'd suggest that you set aside portions of the shared memory segment when you initially set it up that are the right sizes for what you need. Then have one of the processes compute and store the pointers to the areas before either of them want to use the areas. This will give you "static" areas that you can use. Remember that using pointers in shared memory segments assumes that all of the processes attach the segment at the same virtual address in their address spaces. If you don't ensure this, then the pointers will point to different places, and that'll surely mess things up. I always use offsets from the beginning the segment and compute the pointers I need by adding the offset to the attach address in this process. If I need to access the pointers often, I'll save them in global pointers and compute them just once. This avoids the problems caused by different processes attaching the shared memory to different addresses in their process space. Shared memory can be used to solve lots of problems, but sometimes it's not easy to set it up the right way. Good luck. -- Greg Hunt Internet: hunt@dg-rtp.rtp.dg.com DG/UX Kernel Development UUCP: {world}!mcnc!rti!dg-rtp!hunt Data General Corporation Research Triangle Park, NC, USA These opinions are mine, not DG's.