/* * Exemplo de uso de memória compartilhada. * Pai e filho irão se sincronizar por meio de mutex locks e variáveis * de condição. */ #include #include #include #include #include #include #include typedef struct sh_struct { pthread_mutex_t mutex; pthread_cond_t cond; int flag; } sh_struct; #define SHMSZ sizeof(sh_struct) int main() { int shmid; key_t key; char *shm; sh_struct* s; pthread_mutexattr_t mutexattr; pthread_condattr_t condattr; /* 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); } s = (sh_struct*) shm; pthread_mutexattr_init(&mutexattr); pthread_mutexattr_setpshared(&mutexattr, 1); pthread_mutex_init(&s->mutex, &mutexattr); pthread_condattr_init(&condattr); pthread_condattr_setpshared(&condattr, 1); pthread_cond_init(&s->cond, &condattr); s->flag = 0; if (fork() != 0) { pthread_mutex_lock(&s->mutex); s->flag = 1; pthread_cond_signal(&s->cond); pthread_mutex_unlock(&s->mutex); } else { pthread_mutex_lock(&s->mutex); while (s->flag == 0) pthread_cond_wait(&s->cond, &s->mutex); pthread_mutex_unlock(&s->mutex); printf("Filho recebeu sinal do pai.\n"); } shmctl(shmid, IPC_RMID, NULL); shmdt(shm); return 0; }