Path: utzoo!attcan!uunet!spool2.mu.edu!think.com!snorkelwacker.mit.edu!bloom-beacon!eru!hagbard!sunic!mcsun!unido!pkinbg!caxwgk@pkinbg.UUCP From: caxwgk@pkinbg.UUCP (Wolfgang Kuehnel ) Newsgroups: comp.unix.questions Subject: Re: Shared memory and malloc Message-ID: <943@scaxs2.pkinbg.uucp> Date: 14 Jan 91 08:00:40 GMT References: <1990Dec19.144959.16561@dg-rtp.dg.com> Sender: caxwgk@pkinbg.uucp Lines: 43 From article <1990Dec19.144959.16561@dg-rtp.dg.com>, by hunt@dg-rtp.rtp.dg.com (Greg Hunt): > 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()). I've once written a set of routines that manage the above problem. They create a SHM of a given size and attach the process to the SHM. Identi- fication of the SHM is done by a file read by all involved processes. The are routines to shm_alloc() , shm_realloc(), shm_free() the amount of memory created by shm_init(). So a process can alloc() a portion of the SHM. The data in this part of the SHM can be accessed by other processes when the exchange information about where the data starts. So there has to be some additional application specific mechanism to "broadcast" the adresses of the malloc-ed memeory. The shm_malloc() and shm_free() routines are based on the malloc() and free() routines published in chapter eight of Kernighan-Ritchies basic book on the C language. The difference is that a limited amount of memory is handled, there is no sbrk() for SHM. You can alter the functions yourself, (beware of a bug in K+R free()- function, at least in the german translation) or I can post the stuff. Possibly on Friday. Wolfgang