📄 semaforo.h
字号:
#include <sys/types.h>#include <sys/ipc.h>#include <sys/sem.h>#include <malloc.h>#include <errno.h>void Crea_Semaforo (key_t No_Semaforo, int valor_inicial){ // semget regresa el id del semaforo asociado a la llave int semid = semget(No_Semaforo, 1, 0666|IPC_CREAT|IPC_EXCL); if ((semid == -1) && (errno == EEXIST)) { printf("\nEl semaforo ya existe. %d\t", errno); } else { //Si ya existe el semaforo ya no se inicializa. //Inicializacion del semaforo union semun{ int val; struct semid_ds *buf; ushort *array; }arg; arg.val = valor_inicial; int returnValue = semctl(semid, 0 , SETVAL, arg); if(returnValue != 0) printf("\nError al ejecutar semop, errno= %d\n", errno); } }int obtenSemaforo(key_t No_Semaforo){ int semid = semget(No_Semaforo, 1, 0666|IPC_CREAT); if ((semid == -1) && (errno == EEXIST)) { printf("Key repetida!!! %d", errno); } else if (semid == -1) { printf("%d", errno); } return semid;}//V es la operacion que incrementa el semaforo.//Regresa -1 si hay error en semopint V(int semid) { struct sembuf operacion[1]; operacion[0].sem_num = 0; operacion[0].sem_op = 1; operacion[0].sem_flg = 0; int returnValue = semop(semid, operacion, 1); if(returnValue == -1) { return -1; } return 0;}//P es la operacion que lo decrementa (si no es 0)//Regresa -1 si hay error en semopint P(int semid) { struct sembuf operacion[1]; operacion[0].sem_num = 0; operacion[0].sem_op = -1; operacion[0].sem_flg = 0; int rtrn = semop(semid, operacion, 1); if(rtrn == -1) { return -1; } return 0;}void destruyeSemaforo (int semid){ union semun{ int val; struct semid_ds *buf; ushort *array; }arg; int rtrn = semctl(semid, 0,IPC_RMID,arg); if (rtrn == -1){ printf("\The semctl call failed, error number = %d\n",errno); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -