/* * Exemplo de uso de memória compartilhada. * Pai e filho irão se sincronizar por meio de espera ocupada. */ #include #include #include #include #include #include #define SHMSZ 2 int main() { int shmid; key_t key; char *shm; /* 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); } /* Segmento é associado ao espaço de endereçamento */ if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) { perror("shmat"); exit(1); } shm[0] = '\0'; shm[1] = '\0'; if (fork() != 0) { shm[0] = '*'; printf("Esperando o filho\n"); while (shm[1] != '*') sleep(1); } else { sleep(10); shm[1] = '*'; printf("Esperando o pai\n"); while (shm[0] != '*') sleep(1); } shmctl(shmid, IPC_RMID, NULL); shmdt(shm); return 0; }