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;
- int *punteromemoria[4]; //Hay que declararlas globales para la manejadora
- void*tempp;
- 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,i,j;
- //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*punteroMemoriaTemp;
- idmemoria = shmget(IPC_CREAT,PARKING_getTamaNoMemoriaCompartida()+(320*sizeof(int)),IPC_CREAT | 0600);
- tempp = shmat(idmemoria,0,0);
- punteroMemoriaTemp = (int*)(tempp + PARKING_getTamaNoMemoriaCompartida());
- for(i=0; i<4; i++){
- punteromemoria[i] = punteroMemoriaTemp + (i*80);
- for(j=0;j<80;j++){
- //punteromemoria[algoritmo][posicion]
- punteromemoria[i][j]=0;
- }
- }
- struct PARKING_mensajeBiblioteca msg;
- idbuzon = msgget(IPC_PRIVATE,IPC_CREAT | 0600);
- //CREACION DE LAS CARRETERAS
- 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);
- }
- msg.tipo = 1800+i;
- msgsnd(idbuzon, &msg, sizeof(PARKING_mensajeBiblioteca)-sizeof(long) , 0);
- }
- //FIN CREACION DE LAS CARRETERAS
- //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(15);
- pause();
- 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){
- msgrcv(idbuzon,&mensajebb,sizeof(PARKING_mensajeBiblioteca)-sizeof(long),800+PARKING_getAlgoritmo(mensajebb.hCoche)+(PARKING_getNUmero(mensajebb.hCoche)*1000),0);
- 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();
- finalizar(666);
- break;
- }
- }
- break;
- }
- //FIN DE CREACION DE PROCESOS
- return 0;
- }
- void finalizar(int signall)
- {
- int i;
- printf("\n");
- for(i=1;i<choferes+1;i++){
- kill(vectorPIDS[i], SIGKILL);
- }
- //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");
- }*/
- if(shmdt(tempp) == -1)//Liberamos la memoria compartida
- {
- printf("Error liberando el puntero\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");
- }
- exit(0);
- //signal(SIGINT,finalizar); //Dejamos de nuevo la senal SIGINT asociada a la funcion finalizar
- }
- /*void manejadoraNada(int ss){
- exit(0);
- }*/
- 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){
- PARKING_fin(1);
- exit(0);
- }
- int primero(HCoche hc){
- int i,j,k;
- int flagOcupado=0;
- for (i=0;i<80;i++){
- if(punteromemoria[1][i] == 0){ //Posicion libre
- for(j=0;j<PARKING_getLongitud(hc);j++){
- i = i + 1;
- if(i>79 || punteromemoria[1][i] == 1){
- flagOcupado=1;
- j=PARKING_getLongitud(hc);
- }
- }
- if (flagOcupado==1){//no se puede aparcar
- flagOcupado=0;
- }
- else {//si se puede aparcar
- for (k=0;k<PARKING_getLongitud(hc);k++){
- i=i-1;
- punteromemoria[1][i]=1;
- }
- //i=i-PARKING_getLongitud(hc);
- //printf("POSICION %d\n", i);
- return i;
- }
- }
- }
- 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 avisar al siguiente coche de que puede aparcar
- struct PARKING_mensajeBiblioteca mensajebb;
- mensajebb.tipo = 800+PARKING_getAlgoritmo(mensajebb.hCoche)+((PARKING_getNUmero(mensajebb.hCoche)+1)*1000);
- msgsnd(idbuzon, &mensajebb, sizeof(PARKING_mensajeBiblioteca)-sizeof(long) , 0);
- //printf("Funcion fCommit");
- //struct PARKING_mensajeBiblioteca mensajebb;
- //msgrcv(idbuzon,&mensajebb,sizeof(PARKING_mensajeBiblioteca)-sizeof(long),PARKING_MSG,0);
- }
- void manejadoraPermisoAvance(HCoche hc){
- struct PARKING_mensajeBiblioteca mensajebb;
- int tipo,i,posicion;
- char errorTag[80];
- //Algoritmo para evitar choques en el desaparcamiento
- if(PARKING_getY(hc)==1 && PARKING_getY2(hc)==2){
- for(i=PARKING_getX(hc)+PARKING_getLongitud(hc)-1;i>=PARKING_getX(hc);i--){
- if(msgrcv(idbuzon, &mensajebb, sizeof(PARKING_mensajeBiblioteca)-sizeof(long),tipoMensaje(i, PARKING_getAlgoritmo(hc)), 0)==-1){
- perror(errorTag);
- exit(-1);
- }
- }
- }
- else if(PARKING_getY(hc)==2 && PARKING_getY2(hc)==2 && PARKING_getX(hc)+PARKING_getLongitud(hc)>=0 && PARKING_getX(hc)+PARKING_getLongitud(hc)<80){
- if(msgrcv(idbuzon, &mensajebb, sizeof(PARKING_mensajeBiblioteca)-sizeof(long), tipoMensaje(PARKING_getX2(hc), PARKING_getAlgoritmo(hc)), 0)==-1){//Carretera ocupada
- perror(errorTag);
- exit(-1);
- }
- }
- }
- void manejadoraPermisoAvanceCommit(HCoche hc){
- int posicion,k;
- char errorTag[80];
- int i;
- struct PARKING_mensajeBiblioteca mensajebb;
- //Actualizar cuando se libere la memoria compartida
- if(PARKING_getY(hc)==2 && PARKING_getY2(hc)==1){
- for (k=PARKING_getX(hc);k<PARKING_getX(hc)+PARKING_getLongitud(hc);k++){
- punteromemoria[PARKING_getAlgoritmo(hc)][k]=0;
- }
- }else if(PARKING_getY(hc)==2 && PARKING_getY2(hc)==2 && PARKING_getX(hc)+PARKING_getLongitud(hc)>=0 && PARKING_getX(hc)+PARKING_getLongitud(hc)<80){
- mensajebb.tipo = tipoMensaje(PARKING_getX(hc)+PARKING_getLongitud(hc), PARKING_getAlgoritmo(hc));
- if(msgsnd(idbuzon, &mensajebb, sizeof(PARKING_mensajeBiblioteca)-sizeof(long),0)==-1){//Carretera ocupada
- perror(errorTag);
- exit(-1);
- }
- }else if(PARKING_getY(hc)==1 && PARKING_getY2(hc)==2){
- for(i=PARKING_getX(hc)+PARKING_getLongitud(hc)-1;i>=PARKING_getX(hc);i--){
- mensajebb.tipo = tipoMensaje(i, PARKING_getAlgoritmo(hc));
- if(msgsnd(idbuzon, &mensajebb, sizeof(PARKING_mensajeBiblioteca)-sizeof(long),0)==-1){
- perror(errorTag);
- exit(-1);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement