Last active
May 25, 2016 07:24
-
-
Save RicardoLara/d9847edd98d6fcab45d0377d2340fb1c to your computer and use it in GitHub Desktop.
Consumidor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <pthread.h> | |
| #include <errno.h> | |
| #include <sys/types.h> | |
| #include <sys/sem.h> | |
| #include <sys/types.h> | |
| #include <sys/ipc.h> | |
| #include <sys/shm.h> | |
| #include <unistd.h> | |
| #define CONSUMIDOR 1 | |
| #define PRODUCTOR 0 | |
| typedef struct mystruct{ | |
| char tipo; //Llam o msg | |
| char msg[100]; | |
| char edo; //Vacio / Lleno | |
| char destino; | |
| } memoria; | |
| void wait(int who, int control){ | |
| struct sembuf operacion; | |
| operacion.sem_num = who; | |
| operacion.sem_op = -1; | |
| operacion.sem_flg = SEM_UNDO; | |
| semop(control, &operacion, 1 ); | |
| } | |
| void signal(int who, int control){ | |
| struct sembuf operacion; | |
| operacion.sem_num = who; | |
| operacion.sem_op = 1; | |
| operacion.sem_flg = SEM_UNDO; | |
| semop(control, &operacion, 1 ); | |
| } | |
| int main(){ | |
| int shmid,clean; | |
| memoria *globales; | |
| key_t key; | |
| if ((key = ftok("1.c", 'J')) == -1) { | |
| perror("ftok"); | |
| exit(1); | |
| } | |
| if ((shmid = shmget(key, 20 * sizeof(memoria), (memoria)IPC_CREAT | 0666)) < 0) { | |
| perror("shmget"); | |
| exit(1); | |
| } | |
| if ((globales = (memoria)shmat(shmid, 0, 0)) == (int*)-1) { | |
| perror("shmat"); | |
| exit(1); | |
| } | |
| if ( (globales[0] = semget(key, 20, IPC_CREAT | 0600)) < 0 ) { | |
| printf("Error SEMGET\n"); | |
| exit(-1); | |
| } | |
| //Verificar cuando actua un consumidor | |
| /* | |
| for (size_t k = 0; k < 30; k++) { | |
| wait(CONSUMIDOR,globales[0]); | |
| printf("Consumidor: ["); | |
| for (size_t g = 0; g < 10; g++){ | |
| printf("%d", globales[g+2] + 1); // Cada operacion lee 10 veces | |
| if(g!=9) printf(","); | |
| } | |
| printf("]\n"); | |
| signal(PRODUCTOR,globales[0]); | |
| } | |
| */ | |
| /* | |
| if(semget(key, 2, 0600) >= 0){ // Cleanup | |
| printf("\nCLEANUP: Semaforo y Memoria Liberados\n"); | |
| if (semctl(globales[0], 0, IPC_RMID, NULL) == -1) { | |
| perror("semctl"); | |
| exit(1); | |
| } | |
| shmctl(shmid, IPC_RMID, 0); | |
| } | |
| */ | |
| shmdt(globales); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment