#include #include #include #include /* sem_block.c - a program that creates and blocks on a semaphore **/ /* usage: sem_block key amt * action: program creates a semaphore with key `key', sets its initial * value to zero then blocks waiting to decrement it by amt */ #define oops(m,x) { perror(m); exit(x); } union semun { int val; struct semid_ds *buf; ushort *array; }; main(int ac, char *av[]) { int semid; /* an id */ union semun sem_info; /* some properties */ struct sembuf action; /* action for the sem */ int amount; /* amount to decrement */ if ( ac != 3 ){ printf("usage: sem_block key\n"); exit(1); } amount = atoi(av[2]); /* * create or connect to a semset with 1 semaphore in it */ semid = semget( atoi(av[1]), 1, IPC_CREAT|0666 ); if( semid == -1 ) oops("semget",2); /* * initialize value of semaphore number 0 to 0 */ sem_info.val = 0; if ( semctl(semid, 0, SETVAL, sem_info) == -1 ) oops("semctl",3); /* * prepare the block-to-decrement command */ action.sem_num = 0; /* action for semaphore 0 */ action.sem_flg = SEM_UNDO; /* auto clean up */ action.sem_op = -amount; /* DECREMENT SEMAPHORE */ /* * about to block on request to decrement... */ printf("sem_block: waiting to decrement semaphore by %d\n", amount); if ( semop( semid, &action, 1) == -1 ) oops("semop",10); printf("sem_block DONE!\n"); semctl(semid, 0, IPC_RMID, 0); /* delete it */ }