shared memory

Mark Lawrence mark at DRD.Com
Sat Sep 22 04:33:26 AEST 1990


andrew at 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 <sys/types.h>
#include <sys/shm.h>
#include <memory.h>
/*
    +-----------------------------------------------------------------
    | 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 at DRD.Com uunet!apctrc!drd!mark$B!J%^!<%/!!!&%m!<%l%s%9!K(B



More information about the Comp.unix.programmer mailing list