Xref: utzoo comp.lang.c:32029 comp.unix.programmer:75 Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!apctrc!drd!mark From: mark@DRD.Com (Mark Lawrence) Newsgroups: comp.lang.c,comp.unix.programmer Subject: Re: shared memory Keywords: shared memory Message-ID: <1990Sep21.183326.13116@DRD.Com> Date: 21 Sep 90 18:33:26 GMT References: <566@gestetner.oz> Organization: DRD Corporation Lines: 84 andrew@gestetner.oz (Andrew Hunt) wrote: } I am having problems with UNIX shared memory system functions } (shmget, shmctl, shmop) - our system is SUN O/S 4.0.x. } I am trying to attach some data to a shared memory identifier. } } assign global_start_address } assign global_size } } global_shmid = shmget(IPC_PRIVATE,global_size,0777|IPC_CREAT); } } shmat(global_shmid,global_start_address,SHM_RDONLY); shmat returns the address. You can't tell it where you want it. Then dereference the members of interest in each process using the Psh pointer. An example: #include #include #include /* +----------------------------------------------------------------- | declarations of scope process */ extern int errno; /* system call err status */ extern const char *strerror(int); typedef struct { int foo; float bar; short gex; double snark; } SHMEM; #define SHMEM_k 0x4444 /* arbitrary key */ #define SHMEM_PERMISSION 0666 /* rw-rw-rw */ SHMEM *Psh; /* +----------------------------------------------------------------- | declarations of scope file */ static int shmid; /* +----------------------------------------------------------------- | executable code begins here */ static void CrynDie(char *who, char *what) { fprintf(stderr, "\n\n%s: Fatal error from %s, %s", who, what, strerror(errno)); exit(1); } /* * The CreateShMem function is to be called only by one process at system * startup. It will create shared memory for the system. That process must * then AttachShMem. All other processes must use the AttachShMem function * only which will get and attach shared memory. */ void CreateShMem(char *caller) { SHMEM *pshmem; if ((shmid = shmget(SHMEM_k, sizeof(SHMEM), IPC_CREAT | SHMEM_PERMISSION)) == -1) CrynDie(caller, "Shared memory creation failed -- fatal error"); /* initialize the shared memory block to all NULLs */ if ((pshmem = (SHMEM *) shmat(shmid, 0, 0)) == (SHMEM *) - 1) CrynDie(caller, "attach failed"); memset((char *) pshmem, '\0', sizeof(SHMEM)); shmdt((char *) pshmem); } void AttachShMem(char *caller) { if ((shmid = shmget(SHMEM_k, sizeof(SHMEM), SHMEM_PERMISSION)) == -1) CrynDie(caller, "Get shared memory id failed"); if ((Psh = (SHMEM *) shmat(shmid, 0, 0)) == (SHMEM *) - 1) CrynDie(caller, "attach failed"); } -- mark@DRD.Com uunet!apctrc!drd!mark$B!J%^!<%/!!!&%m!<%l%s%9!K(B