/* * Exemplo de uso de memória compartilhada. Associação do mesmo * segmento próximo à área de pilha e próximo à área de dados. */ #include #include #include #include #include #define SHMSZ 27 /* Será arredondado para um múltiplo de PAGE_SIZE */ char str_global[10]; int main() { int shmid; key_t key; char str_local[10]; char *shm_dados, *shm_pilha; char c, *s; /* Chave arbitrária para o segmento compartilhado */ key = 5677; /* Criação do segmento de memória e obtenção do seu identificador. */ if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) { perror("shmget"); exit(1); } /* Tentativa de associação próximo à área de pilha. */ if ((shm_pilha = shmat(shmid, str_local-0x100000, SHM_RND)) == (char *) -1) { printf("shmat at 0x%x\n", (unsigned int) str_local-0x100000); perror("shmat"); exit(1); } /* Tentativa de associação próximo à área de dados. */ if ((shm_dados = shmat(shmid, str_global+0x10000, SHM_RND)) == (char *) -1) { printf("shmat at 0x%x\n", (unsigned int) str_global+0x1000); perror("shmat"); } printf("str_local = 0x%x\n", (unsigned int) str_local); printf("shm_pilha = 0x%x\n", (unsigned int) shm_pilha); printf("shm_dados = 0x%x\n", (unsigned int) shm_dados); printf("str_global = 0x%x\n", (unsigned int) str_global); printf("main = 0x%x\n", (unsigned int) main); /* Preenche o segmento com o alfabeto */ s = shm_pilha; for (c = 'a'; c <= 'z'; c++) *s++ = c; *s = '\0'; /* Verifica o preenchimento nos dois endereço */ printf("SHM_Pilha: %s\n", shm_pilha); printf("SHM_Dados: %s\n", shm_dados); return 0; }