Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include "parking.h"
- #include <string.h>
- #include <sys/sem.h>
- #include <sys/msg.h>
- #include <sys/shm.h>
- #include <signal.h>
- #include <unistd.h>
- int primero(HCoche hc);
- int siguiente(HCoche hc);
- int mejor(HCoche hc);
- int peor(HCoche hc);
- void manejadoraTiempo (int signall);
- int tipoMensaje(long posicionAcera, int algoritmo);
- void manejadorafCommit(HCoche hc);
- void manejadoraPermisoAvance(HCoche hc);
- void manejadoraPermisoAvanceCommit(HCoche hc);
- int idsemaforo;
- int idbuzon;
- int idmemoria;
- char *punteromemoria; //Hay que declararlas globales para la manejadora
- void finalizar(int signall);
- int flag=1;
- int vectorPIDS[100];
- int choferes;
- int main (char argc, char * argv[]){
- //INICIO DE LA FASE DE RECOGIDA DE ARGUMENTOS
- int velocidad, debug=0, prioridadA=0, prioridadD=0;
- struct sigaction ss;
- TIPO_FUNCION_LLEGADA f_llegadas[4] = {primero, siguiente, mejor, peor};
- int posicion,algoritmo,k;
- //ESTABLECEMOS LA FUNCION QUE TIENE EL SIGINT EN EL MAIN
- /*void salidaSIGINT;
- salidaSIGINT = exit(0);
- signal(SIGINT, salidaSIGINT);*/ //PREGUNTAR A FRAN
- //FIN ESTABLECEMOS LA FUNCION QUE TIENE EL SIGINT EN EL MAIN
- //DECLARACION DE SENALES Y MASCARA
- /*sigset_t conjuntoTotal;
- sigfillset(&conjuntoTotal);
- sigprocmask(SIG_SETMASK,&conjuntoTotal,NULL); //De esta forma bloqueamos todas las senales*/
- sigset_t senalesSinSIGINTSIGALRM;
- sigfillset(&senalesSinSIGINTSIGALRM);
- sigdelset(&senalesSinSIGINTSIGALRM,SIGINT); //De esta forma creamos un conjunto de senales menos el SIGINT, //haciendo despues sigsuspend para cambiar las senales que estan bloqueadas por este conjunto //que no tiene SIGINT (es decir, solo SIGINT no esta bloqueada)
- sigdelset(&senalesSinSIGINTSIGALRM,SIGALRM);
- sigprocmask(SIG_SETMASK,&senalesSinSIGINTSIGALRM,NULL);
- sigfillset(&ss.sa_mask);//LLenamos la mascara con las señales
- sigdelset(&ss.sa_mask,SIGINT);//quita de la máscara la señal SIGINT
- sigdelset(&ss.sa_mask,SIGALRM);
- //FIN DECLARACION DE SENALES Y MASCARA
- if (argc !=3 && argc !=4 && argc !=5){//El primer argumento es el nombre del programa
- printf("Error en el número de parámetros\n");
- return -1;
- }
- else if (argc ==3){
- printf("Dos argumentos: %s %s\n", argv[1], argv[2]);
- velocidad = atoi(argv[1]);
- choferes = atoi(argv[2]);
- if (velocidad<0){
- printf("Velocidad errónea (menor que 0)\n");
- return -1;
- }
- else if (choferes<=0){
- printf("Número de chóferes erróneo (menor o igual que 0)\n");
- return -1;
- }
- else {
- printf("Debug desactivado\n");
- }
- }
- else if (argc==4) {
- printf("Tres argumentos: %s %s %s \n", argv[1], argv[2], argv[3]);
- velocidad = atoi(argv[1]);
- choferes = atoi(argv[2]);
- //DEBUG DE ERRORES PARA BORRAR AL FINAL
- printf("Velocidad = %d\n", velocidad);
- printf("Chóferes = %d\n",choferes);
- printf("Tercer argumento : %s\n", argv[3]);
- //DEBUG DE ERRORES PARA BORRAR AL FINAL
- if (velocidad<0){
- printf("Velocidad errónea (menor que 0)\n");
- return -1;
- }
- if (choferes<=0){
- printf("Número de chóferes erróneo (menor o igual que 0)\n");
- return -1;
- }
- if (!strcmp(argv[3],"D") || !strcmp(argv[3],"d")){
- debug=1;
- printf("Debug activado\n");
- }
- else if (!strcmp(argv[3],"PD") || !strcmp(argv[3],"pd")){
- prioridadD=1;
- printf("Prioridad desaparcar\n");
- }
- else if (!strcmp(argv[3],"PA") || !strcmp(argv[3],"pa")){
- prioridadA=1;
- printf("Prioridad aparcar\n");
- }
- }
- else if (argc==5) {
- printf("Cuatro argumentos: %s %s %s %s\n", argv[1], argv[2], argv[3], argv[4]);
- velocidad = atoi(argv[1]);
- choferes = atoi(argv[2]);
- //DEBUG DE ERRORES PARA BORRAR AL FINAL
- printf("Velocidad = %d\n", velocidad);
- printf("Chóferes = %d\n",choferes);
- printf("Tercer argumento : %s\n", argv[3]);
- printf("Cuarto argumento: %s\n", argv[4]);
- //DEBUG DE ERRORES PARA BORRAR AL FINAL
- if (velocidad<0){
- printf("Velocidad errónea (menor que 0)\n");
- return -1;
- }
- if (choferes<=0){
- printf("Número de chóferes erróneo (menor o igual que 0)\n");
- return -1;
- }
- //Entramos al tercer argumento
- if (!strcmp(argv[3],"D") || !strcmp(argv[3],"d")){
- debug=1;
- printf("Debug activado\n");
- }
- else if (!strcmp(argv[3],"PD") || !strcmp(argv[3],"pd")){
- prioridadD=1;
- printf("Prioridad desaparcar\n");
- }
- else if (!strcmp(argv[3],"PA") || !strcmp(argv[3],"pa")){
- prioridadA=1;
- printf("Prioridad aparcar\n");
- }
- //Entramos al cuarto argumento
- if ((!strcmp(argv[4],"D") || !strcmp(argv[4],"d") && debug==0)){
- debug=1;
- printf("Debug activado\n");
- }
- else if ((!strcmp(argv[4],"D") || !strcmp(argv[4],"d") && debug==1)){
- printf("Debug doblemente activado. ERROR.\n");
- return -1;
- }
- if ((!strcmp(argv[4],"PD") || !strcmp(argv[4],"pd")) && prioridadA==0 && prioridadD==0){
- prioridadD=1;
- printf("Prioridad desaparcar\n");
- }
- else if (!strcmp(argv[4],"PD") || !strcmp(argv[4],"pd") && (prioridadA==1 || prioridadD==1)){
- printf("Error al establecer prioridades\n");
- return -1;
- }
- if ((!strcmp(argv[4],"PA") || !strcmp(argv[4],"pa")) && prioridadA==0 && prioridadD==0){
- prioridadA=1;
- printf("Prioridad aparcar\n");
- }
- else if (!strcmp(argv[4],"PA") || !strcmp(argv[4],"pa") && (prioridadA==1 || prioridadD==1)){
- printf("Error al establecer prioridades\n");
- return -1;
- }
- }
- //FIN DE LA FASE DE RECOGIDA DE ARGUMENTOS
- //INICIO DE LA FASE DE DECLARACIÓN DE MECANISMOS IPC
- int numSem;
- numSem=PARKING_getNSemAforos();
- idsemaforo = semget (IPC_PRIVATE,numSem+choferes, IPC_CREAT | 0600);
- printf("El número de semaforos es %d \n",numSem);
- int tamanoMemoria;
- tamanoMemoria=PARKING_getTamaNoMemoriaCompartida();
- idmemoria = shmget(IPC_CREAT,tamanoMemoria,IPC_CREAT | 0600);
- punteromemoria = (char *) shmat(idmemoria,0,0);
- printf("ID MEMORIA: %d", idmemoria);
- idbuzon = msgget(IPC_PRIVATE,IPC_CREAT | 0600);
- //CREACION DE LAS ACERAS
- for(algoritmo=0;algoritmo<4;algoritmo++){
- struct acera;
- for(posicion=0;posicion<80;posicion++){
- acera.pos=tipoMensaje(posicion,algoritmo);
- msgsnd(idbuzon, &acera.pos, sizeof(acera), MSG_NOERROR);
- }
- }
- //FIN CREACION DE LAS ACERAS
- //FIN DE LA FASE DE DECLARACION DE MECANISMOS IPC
- PARKING_inicio(velocidad, f_llegadas, idsemaforo, idbuzon, idmemoria, debug);
- //CREACION DE PROCESOS
- int valor_devuelto, valor_choferes;
- TIPO_FUNCION_APARCAR_COMMIT fCommit = &manejadorafCommit;
- TIPO_FUNCION_PERMISO_AVANCE permisoAvance = &manejadoraPermisoAvance;
- TIPO_FUNCION_PERMISO_AVANCE_COMMIT permisoAvanceCommit = &manejadoraPermisoAvanceCommit;
- valor_devuelto=fork(); //Case 0 es para el hijo y default para el padre
- switch (valor_devuelto){
- case -1:
- perror("ERROR al crear el hijo");
- break;
- case 0:
- signal(SIGALRM, manejadoraTiempo);
- alarm(1);
- while(1);
- break;
- default:
- vectorPIDS[0]=getppid();
- for(k=0;k<1;k++)//Bucle de creacion de los choferes
- {
- valor_choferes=fork();
- vectorPIDS[k+1]=valor_choferes;
- switch (valor_choferes){
- case -1:
- perror("ERROR al crear chofer");
- break;
- case 0://CODIGO DE LOS CHOFERES
- {
- struct PARKING_mensajeBiblioteca mensajebb;//Mensaje que se recibe de la biblioteca
- //printf("PID: %d\n" , vectorPIDS[k]);
- while(1){
- msgrcv(idbuzon,&mensajebb,sizeof(PARKING_mensajeBiblioteca)-sizeof(long),PARKING_MSG,0);
- if(mensajebb.subtipo==1){
- PARKING_aparcar(mensajebb.hCoche,0,fCommit,
- permisoAvance,
- permisoAvanceCommit);
- }
- if(mensajebb.subtipo==2){
- PARKING_desaparcar(mensajebb.hCoche,0,
- permisoAvance,
- permisoAvanceCommit);
- }
- }
- break;
- }
- default:
- signal(SIGINT,finalizar);
- PARKING_simulaciOn();
- break;
- }
- }
- break;
- }
- //FIN DE CREACION DE PROCESOS
- return 0;
- }
- void finalizar(int signall)
- {
- int i;
- printf("\n");
- signal(SIGINT, SIG_IGN);//Desactivamos el sigint dentro de la funcion finalizar
- if(semctl(idsemaforo,0,IPC_RMID) == -1)//Eliminamos el lote de semáforos
- {
- printf("Error eliminando el lote de semaforos\n");
- }
- else
- {
- printf("Lote de semaforos eliminado\n");
- }
- if(msgctl(idbuzon,IPC_RMID,0) == -1)//Eliminamos el buzon
- {
- printf("Error eliminando el buzon\n");
- }
- else
- {
- printf("Buzon eliminado\n");
- }
- if(shmdt(punteromemoria) == -1)//Liberamos la memoria compartida
- {
- printf("Error liberando la zona de memoria compartida\n");
- }
- else
- {
- printf("Zona de memoria compartida liberada\n");
- }
- if(shmctl(idmemoria,IPC_RMID,0) == -1)//Eliminamos la memoria compartida
- {
- printf("Error eliminando la zona de memoria compartida\n");
- }
- else
- {
- printf("Zona de memoria compartida eliminada con exito\n");
- }
- for(i=1;i<choferes+1;i++){
- kill(vectorPIDS[i], SIGKILL);
- }
- signal(SIGINT,finalizar); //Dejamos de nuevo la senal SIGINT asociada a la funcion finalizar
- }
- int tipoMensaje(long posicionAcera, int algoritmo){
- return (posicionAcera*100) + algoritmo+1;
- }
- /*int *tipoMensajeBiblioteca(int posicionCodificada){
- int vector[2];
- vector[0]=posicionCodificada/10;
- vector[1]=posicionCodificada%10;
- return vector;
- }*/
- void manejadoraTiempo (int signall){
- static int contador = 0;
- //printf("\nHOLA BUENAS TARDES\n");
- contador++;
- if (contador==5){
- //flag = 0;
- PARKING_fin(0);
- kill(vectorPIDS[0],SIGINT);
- }
- alarm(1);
- }
- int primero(HCoche hc){
- int i,j;
- int posicionRecibida;
- int flagOcupado=0;
- struct PARKING_mensajeBiblioteca mensajeComprobacion;
- for (i=0;i<80;i++){
- posicionRecibida=i*10 + 1;
- if((msgrcv(idbuzon, &mensajeComprobacion, sizeof(PARKING_mensajeBiblioteca)-sizeof(long), posicionRecibida,0)!=-1)){ //Mensaje encontrado luego esta libre
- for(j=0;j<PARKING_getLongitud(hc);j++){
- posicionRecibida=posicionRecibida+10;
- if(posicionRecibida>791 || (msgrcv(idbuzon, &mensajeComprobacion, sizeof(PARKING_mensajeBiblioteca)-sizeof(long), posicionRecibida,0)==-1)){
- flagOcupado=1;
- j=PARKING_getLongitud(hc);
- }
- }
- if (flagOcupado==1){//no se puede aparcar
- flagOcupado=0;
- }
- else {//si se puede aparcar
- posicionRecibida=posicionRecibida-(PARKING_getLongitud(hc)-1)*10;
- posicionRecibida=posicionRecibida/10;
- printf("POSICION %d\n", posicionRecibida);
- return posicionRecibida;
- }
- }
- }
- return -1;
- }
- int siguiente(HCoche hc){
- return -2;
- }
- int mejor(HCoche hc){
- return -2;
- }
- int peor(HCoche hc){
- return -2;
- }
- void manejadorafCommit(HCoche hc){ //Sirve para que los coches aparquen en orden
- printf("Funcion fCommit");
- //struct PARKING_mensajeBiblioteca mensajebb;
- //msgrcv(idbuzon,&mensajebb,sizeof(PARKING_mensajeBiblioteca)-sizeof(long),PARKING_MSG,0);
- }
- void manejadoraPermisoAvance(HCoche hc){
- printf("Funcion permisoAvance");
- }
- void manejadoraPermisoAvanceCommit(HCoche hc){
- printf("Funcion permisoAvanceCommit");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement