#include #include #include #include #include #include /* For O_* constants */ #include /* For mode constants */ #include char * semaphore_name_a = "/il_mio_semaforo_a"; char * semaphore_name_b = "/il_mio_semaforo_b"; sem_t * semaphore_a; sem_t * semaphore_b; int main() { sem_unlink(semaphore_name_a); sem_unlink(semaphore_name_b); semaphore_a = sem_open(semaphore_name_a, O_CREAT, 0600, 0); if (semaphore_a == SEM_FAILED) { perror("sem_open"); exit(1); } semaphore_b = sem_open(semaphore_name_b, O_CREAT, 0600, 0); if (semaphore_b == SEM_FAILED) { perror("sem_open"); exit(1); } printf("[parent] ho creato i due named semaphore\n"); // il semaforo vale 0 // "signaling": // il processo padre dà il via libera al processo figlio // tramite il semaforo switch (fork()) { case -1: perror("fork"); exit(1); case 0: // processo figlio printf("[child] statement b1\n"); printf("[child] prima di sem_post(semaphore_b)\n"); if (sem_post(semaphore_b) != 0) { perror("sem_post"); exit(1); } printf("[child] prima di sem_wait(semaphore_a)\n"); if (sem_wait(semaphore_a) != 0) { perror("sem_wait"); exit(1); } //printf("[child] dopo sem_wait\n"); // procede con statement b printf("[child] statement b2\n"); exit(0); default: // processo padre // sleep(3); printf("[parent] statement a1\n"); // sem.signal() printf("[parent] prima di sem_post(semaphore_a)\n"); if (sem_post(semaphore_a) != 0) { perror("sem_post"); exit(1); } printf("[parent] prima di sem_wait(semaphore_b)\n"); if (sem_wait(semaphore_b) != 0) { perror("sem_wait"); exit(1); } printf("[parent] statement a2\n"); // processo padre aspetta la conclusione del processo figlio wait(NULL); } return 0; }