/* * Exemplo de uso de memória compartilhada. */ #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; 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 dados. */ if ((shm = shmat(shmid, str_global+0x10000, SHM_RND)) == (char *) -1) { printf("shmat at 0x%x\n", (unsigned int) str_global+0x1000); perror("shmat"); } /* Preenche o segmento com o alfabeto */ s = shm; for (c = 'a'; c <= 'z'; c++) *s++ = c; *s = '\0'; printf("Processo servidor: %s\n", shm); printf("shm = 0x%x\n", (unsigned int) shm); return 0; }