///*****************************************************************/ ///* IUT NICE-COTE D'AZUR - Departement INFORMATIQUE - R. CHIGNOLI */ ///* Module DUT M311 Theme IPC POSIX */ ///*****************************************************************/ /// demo_sem.c : Demonstration d'utilisation d'un sémaphore /// usage : commande [-creation] cle /// premier acces : utiliser l'option "-create" /// Depuis bash, utiliser la commande ls -l /dev/shm /// Depuis bash, utiliser la commande rm /dev/shm/* #include #include #include #include #include #include #include #include #include int main(int argc, char *argv[]) { char reponse; int mode, encore = 1; sem_t *sem; if (argc < 3) { fprintf(stderr, "Usage: %s [ -create | -use ] nom_sem\n", argv[0]); exit(1); } if ((argc == 3) && (strcmp (argv[1], "-create") == 0)) { mode = O_RDWR | O_CREAT | O_EXCL; printf ("\nMode creation\n\n"); } else if ((argc == 3) && (strcmp (argv[1], "-use") == 0)) { mode = O_RDWR; printf ("\nMode utilisation\n\n"); } else { fprintf(stderr, "Usage: %s [ -create | -use ] nom\n", argv[0]); exit(2); } sem = sem_open(argv[2], mode, 0600, 1); if (sem == SEM_FAILED) { perror ("open"); exit (3); } while (encore) { printf("W,P,X,Q ? "); reponse = getchar(); __fpurge(stdin); ///... pour bonne gestion du buffer clavier ... switch (reponse) { case 'P': sem_wait (sem); printf("... W OK.\n"); break; case 'V': sem_post (sem); printf("... P OK.\n"); break; case 'X': sem_close (sem); chdir ("/dev/shm"); sem_unlink (argv[2]); printf("\n... Semaphore /dev/shm/sem.%s detruit\n", argv[2]); encore = 0; break; case 'Q': encore = 0; break; default: printf("... Commande incorrecte\n"); } } printf("\n... Bye\n\n"); }