#include #include #include #include #define NO_BUFFER ((char *)-1) #define NONE (-1) extern void byee(int); class Shared { pid_t pid; int shm_id; char *shm_base; public: void * allocate(int size); void destroy(void); }; void * Shared::allocate(int size) { shm_id = shmget(IPC_PRIVATE, size, IPC_CREAT | S_IREAD | S_IWRITE); if (shm_id < 0) { perror ("Shared::allocate shmget"); byee (-1); } shm_base = shmat (shm_id, (char *)0, 0); if (shm_base == NO_BUFFER){ perror ("Shared::allocate shmat"); byee (-1); } pid = getpid(); return (void *) shm_base; }; void Shared::destroy(void) { /* Buffer not yet created */ if (shm_id == NONE) return; if (shmdt (shm_base) == -1) perror ("Shared::destroy shmdt"); if (getpid() != pid) return; /* only the creator should remove */ if (shmctl (shm_id, IPC_RMID, (struct shmid_ds *)0) == -1){ perror ("Shared::destroy shmctl"); } };