Example #1
0
int main() {
    int n, i, j;
    char evento;
    Fila sus, fimSus;

    scanf("%d", &n);
    cria_fila(&sus, &fimSus, n);

    scanf(" %c", &evento);

    while(evento != 'F') {
        //imprime_fila(sus);
        switch (evento) {
            /*Anda a fila e imprime o numero do paciente atendido
            *Obs.: Optou-se por não utilizar novamente a variavel n por se tratarem de
            *variáveis com funções diferentes na resolução do problema*/
            case 'A':
                j = anda_fila(&sus, &fimSus);
                printf("%d\n", j);
                break;

            /*Sendo um caso de emergencia, o paciente i da fila vai para a primeira posicao
            *Obs.: Optou-se por não utilizar novamente a variavel n por se tratarem de
            *variáveis com funções diferentes na resolução do problema*/
            case 'E':
                scanf("%d", &i);
                transpoe_fila(&sus, &fimSus, i);
                break;
        }
        scanf(" %c", &evento);
    }

    libera_fila(&sus, &fimSus);
}
Example #2
0
int main(){
    Fila *fi;
    int z;
    fi = cria_fila();
    int x = insere_fila(fi,2);
    x = insere_fila(fi,3);
    x = insere_fila(fi,4);
    x = insere_fila(fi,5);
    mostra(fi);
    int y = consulta_fila(fi,&z);
    //x = remove_fila(fi);
    fi = inverte_fila(fi);
    /*
    printf("Primeiro valor %d\n",z);
    printf("Tamanho da fila %d",tamanho(fi));
    if(fila_cheia(fi) == 1){
        printf("Esta cheia");
    }else{
        printf("Nao esta cheia!");
    }*/

    //x = verifica_ord(fi);
    return 0;
}
void fila_criada(void){
	CU_ASSERT(cria_fila(&f) == 1);
}
/* funcao para processar a requisicao de um livro */
void requisitar(Livro livros, Utente utentes,Requisit requisit)
{
    int reserva=1,valido=1;
    char opcao;
    Utente aux_u;
    Livro aux_l;
    Requisit aux_r;
    Requisit_str req_aux;
    f_espera aux_fila;

    while (valido==1)
    {
        if(!(aux_u = valida_u(utentes)))
        {
            printf("O codigo de utente introduzido nao existe!\n\n\n");
            valido=0;
            break;
        }

        if(!vagas_u(requisit,aux_u->registo.cod_utente))
        {
            printf("\n\nO utente ja atingiu o limite de requisicoes/reservas!\n\n\n");
            valido=0;
            break;
        }

        if(!(aux_l = valida_l(livros)))
        {
            printf("O codigo do livro introduzido nao existe!\n\n\n");
            valido=0;
            break;
        }

        if((aux_r = pesquisa_lista_r(requisit,aux_l->dados.cod_livro)))
        {
            printf("\n\nO livro encontra-se requisitado!\n\n\n");

            aux_fila = aux_r->info.reserva.primeiro;
            while(aux_fila)
            {
                if(aux_fila->cod_utente==aux_u->registo.cod_utente)
                {
                    printf("O utente ja possui um pedido de reserva para este livro!\n\n\n");
                    reserva=0;
                }

                aux_fila = aux_fila->prox;
            }

            if(reserva==1)
            {
                do {
                printf("Pretende reservar o livro? (S/N): ");
                printf("\n");
                opcao=getchar();
                opcao=toupper(opcao);
                } while (opcao!='S' && opcao != 'N');

                if(opcao=='S')
                {
                    coloca(&aux_r->info.reserva,aux_u->registo.cod_utente);
                    printf("\nO livro foi reservado com sucesso!\n\n\n");
                    gravar_fich(requisit,0);
                    printf("\n\nInformacao guardada em disco.\n\n\n");
                }
            }
            valido=0;
            break;
        }
        break;
    }

    if(valido==1)
    {
        req_aux.cod_livro = aux_l->dados.cod_livro;
        req_aux.cod_utente = aux_u->registo.cod_utente;
        data_actual(&req_aux.data_r);

        cria_fila(&(req_aux.reserva));
        insere_lista_r(requisit,req_aux);

        printf("\n\nO livro foi requisitado com sucesso!\n\n");
        gravar_fich(requisit,aux_l->dados.cod_livro);
        printf("\n\nInformacao guardada em disco.\n\n\n");
    }
}
void constroi(Livro livros, Utente utentes, Requisit requisit)
{
    int aux,teste;
    char nome_aux[MAX];
    Livro_str livro_aux;
    Utente_str utente_aux;
    Requisit_str requisit_aux;
    FILE *livro_f, *utente_f, *requisit_f;

    livro_f = fopen("livros.txt","r");
    utente_f = fopen("utentes.txt","r");
    requisit_f = fopen("requisit.txt","r+");

    /* Ler dados do ficheiro livros.txt para a lista ligada Livro */
    while(1)
    {
        fgets(nome_aux,MAX,livro_f);
        aux = strlen(nome_aux);
        nome_aux[aux-1] = '\0';
        strcpy(livro_aux.nome,nome_aux);
        if(fscanf(livro_f,"%d",&livro_aux.cod_livro)!=1)
        {
            printf("Houve um erro na leitura do ficheiro livros.txt\n\n");
			pause();
            exit(1);
        }

        insere_lista_l(livros,livro_aux);

        if(fscanf(livro_f,"%d",&aux)==EOF)
            break;
    }


/* Ler dados do ficheiro utentes.txt para a lista ligada Utente */
    while(1)
    {
        fgets(nome_aux,MAX,utente_f);
        if(!(aux = strlen(nome_aux)))
        {
            printf("Houve um erro na leitura do ficheiro utentes.txt\n\n");
			pause();
            exit(1);
        }
        nome_aux[aux-1] = '\0';
        strcpy(utente_aux.nome,nome_aux);
        if(fscanf(utente_f,"%d",&utente_aux.cod_utente)!=1)
        {
            printf("Houve um erro na leitura do ficheiro utentes.txt\n\n");
			pause();
            exit(1);
        }

        insere_lista_u(utentes,utente_aux);

        if(fscanf(utente_f,"%d",&aux)==EOF)
            break;
    }


/* Ler dados do ficheiro requisit.txt para a lista ligada Requisit */
    while(1)
    {
        if((teste=fscanf(requisit_f,"%d",&requisit_aux.cod_livro))!=1 && teste!=-1)
        {
            printf("Houve um erro na leitura do ficheiro requisit.txt\n\n");
			pause();
            exit(1);
        }
        if (teste!=-1)
        {
            if(fscanf(requisit_f,"%d",&requisit_aux.cod_utente)!=1)
            {
                printf("Houve um erro na leitura do ficheiro requisit.txt\n\n");
                pause();
                exit(1);
            }
            if(fscanf(requisit_f,"%d/%d/%d",&requisit_aux.data_r.dia,&requisit_aux.data_r.mes,&requisit_aux.data_r.ano)!=3)
            {
                printf("Houve um erro na leitura do ficheiro requisit.txt\n\n");
                pause();
                exit(1);
            }

            cria_fila(&(requisit_aux.reserva));

            while(1)
            {
                if(fscanf(requisit_f,"%d",&aux)!=1)
                {
                    printf("Houve um erro na leitura do ficheiro requisit.txt\n\n");
                    pause();
                    exit(1);
                }
                if (aux!=0)
                    coloca(&(requisit_aux.reserva),aux);
                else break;
            }

            insere_lista_r(requisit,requisit_aux);

            if((fgetc(requisit_f)==EOF))
                break;
        }
        else break;
    }

    fclose(livro_f);
    fclose(utente_f);
    fclose(requisit_f);

}
Example #6
0
void ordenacaoExterna(int numerosArmazenados){

   /* FILE *arqOrdenado;
    arqOrdenado = fopen("arqOrdenado.txt", "r"); //arquivo a ser ordenado*/
    int i = 0;
    int w = 0;
    int z = 0;
    fila fp; // Fila de prioridade
    int *bs; // Buffer de saida
    tipo_buffer *be; // Buffer de entrada
    tipo_nodo aux,auxRetirada;
    int numeroRuns = numerosArmazenados/TAM_RUN; // Runs geradas
    int inserirBufferEntrada;

    if(numerosArmazenados%TAM_RUN > 0) // Se  teve resto tem que gerar mais uma Run pro resto
        numeroRuns++;

    printf("\nQtd de Runs(50 chaves): %d",numeroRuns);

    gerar_runs(numeroRuns,numerosArmazenados);

    //Alocando memoria para os buffers
    bs = (int*)malloc(sizeof(int)*numeroRuns);
    be = (tipo_buffer*)malloc(sizeof(tipo_buffer)*numeroRuns);

    //Criando fila de prioridade
    fp = cria_fila(numeroRuns);

    //---------------------------------ADICIONAR ELEMENTOS NO BUFFER DE ENTRADA
    printf("\n\n2 - Adicionando elementos no buffer de entrada");
    for (i=0;i<numeroRuns;i++){

        be[i].posAtual=0; /* Somente para armazenar o posição corrente do arquivo.
                                Para quando pegar novamente mais um elemento pegar na posição atual */

        //Total de elementos que este buffer podera pegar da RUN
       // if( (i < numeroRuns || numeroRuns == 1) && numerosArmazenados >= 50 )
        if(i!=numeroRuns-1 || (numerosArmazenados % TAM_RUN) == 0)
            be[i].totalElementos = TAM_RUN; // Run completa
        else
            be[i].totalElementos = numerosArmazenados % TAM_RUN; // Run com menos de TAM_RUM

        //Carregando os buffers de entrada e inserindo os itens de cada Run
        inserirBufferEntrada = inserirElementosBufferEntrada(be,i);
        if (!inserirBufferEntrada){
            be[i].posAtualBuffer=-1;
        }else {
            aux.chave = be[i].chave[0];
            aux.run = i;
            be[i].posAtualBuffer++;
            //printf("\nRecebendo aux.chave %d aux.run %d",aux.chave,aux.run);
            insere_fila(fp,aux,numeroRuns); // Coloca na fila o elemento de indice 0 do buffer de entrada
        }
    }

    //-----------------------------------INICIO DA ORDENAÇÃO EXTERNA
    printf("\n\n3 - Realizando ordenação externa");
    w = 0;
    while (fila_vazia(fp)){
        imprime_fila(fp);
        remove_fila(fp,&auxRetirada);
        printf("\nElemento retirado = %d do Buffer de Entrada %d ",auxRetirada.chave,auxRetirada.run);
        bs[w]=auxRetirada.chave;
        w++;

        //verifica se o buffer de saida esta cheio e imprime no arquivo resultado
        if (w==numeroRuns){
            gravar_resultado(bs,w);
            w=0;
        }

        z=0;
        while (z<numeroRuns){
            if (z==auxRetirada.run){
                if (be[z].posAtualBuffer==TAM_BUFFER)
                    if (!carregaBE(auxRetirada.run,be)){
                        be[z].posAtualBuffer=-1;
                        printf("\nBuffer de entrada %d foi carregado!",auxRetirada.run);
                        break;
                    }
                if (be[z].posAtualBuffer < be[z].totalBuffer){
                    auxRetirada.run=z;
                    auxRetirada.chave=be[z].chave[be[z].posAtualBuffer];
                    insere_fila(fp,auxRetirada,numeroRuns);
                    be[z].posAtualBuffer++;
                    printf("\nElemento inserido = %d no Buffer de Entrada %d ",auxRetirada.chave,auxRetirada.run);
                }
                break;
            }
            z++;
        }// fim while

        //getchar();
    }

    //verifica se o buffer de saida possui algum elemento restante e salva no arquivo resultado
    if (w!=0)
        gravar_resultado(bs,w);

//---------------------------------------------------
    imprime_fila(fp);

    //Finalizando a fila de prioridade
    termina_fila(fp);

    printf("\n\Final da Ordenacao Externa");

    //fclose(arqOrdenado);
}
Example #7
0
int main( int argc , char *argv[]) {
	signal(SIGINT, ctrlHandler);


	n_linhas = linhas("localdns.txt");

	#ifdef DEBUG
	printf("Verificacao dos ficheiros presentes.\n");
	#endif

	if(verifica_ficheiros("localdns.txt") == 0) {
		printf("Ficheiro localdns.txt inexistente!\n");
		exit(1);
	}
	if(verifica_ficheiros("config.txt") == 0) {
		printf("Ficheiro config.txt inexistente!\n");
		exit(1);
	}

	#ifdef DEBUG
	printf("Inicializacoes.\n");
	#endif
	unsigned char buf[65536], *reader, *reader2, qname;
	int sockfd, stop;
	struct DNS_HEADER *dns = NULL;
	struct stats stat;

	struct sockaddr_in servaddr, dest;
	socklen_t len;

	int i, np, r;

	cfg_process = 1;
	stats_process = 1;

	pthread_mutex_init(&mutex, NULL);
	pthread_cond_init(&cond, NULL);

	#ifdef DEBUG
	printf("Criacao das Filas Normal e Prioridade e da lista de Domains locais.\n");
	#endif
	Fila fila_normal = cria_fila();
	Fila fila_prioridade = cria_fila();

	Local l_domains = cria_lista();

	// Hora de arranque do Servidor
	time_t clk = time(NULL);
	strcpy(stat.data_hora_arranque, ctime(&clk));

	// Inicializaco Memoria Partilhada
	init_shm();
	
	ptr_config->flag = 0;

	printf("[PAI - MAIN] PID Main = %d PID DO MEU PAI = %d\n", getpid(), getppid());

	char* data;

	#ifdef DEBUG
	printf("Criacao processo de configuracoes.\n");
	#endif
	if ((cfg_process = fork()) == 0) {
		signal(SIGUSR1, handler_CFG);
		#ifdef DEBUG
		printf("RELEASE CFG.\n");
		printf("Mapeamento de localdns.txt.\n");
		#endif
		mapear("localdns.txt");
		#ifdef DEBUG
		printf("Leitura de config.txt para estrutura em memoria partilhada.\n");
		#endif
		file2memory("config.txt");
		if(signal(SIGALRM, SIG_IGN) == SIG_ERR) {
			perror("SIGALRM Ignore error");
			exit(1);
		}
	} else {
		usleep(200000);

		if(signal(SIGUSR1, SIG_IGN) == SIG_ERR) {
			perror("Signal ignore error");
			exit(1);
		}

		#ifdef DEBUG
		printf("RELEASE MAIN.\n");
		#endif

		#ifdef DEBUG
		printf("Extrair enderecos e ip's locais do mmap\n");
		#endif
		token_mmap(l_domains, ptr_config->data);

		// Check arguments
		if(argc <= 1) {
			printf("Usage: %s <port>\n", argv[0]);
			exit(1);
		}
		
		// Get server UDP port number
		int port = atoi(argv[1]);
		
		if(port <= 0) {
			printf("Usage: %s <port>\n", argv[0]);
			exit(1);
		}

		// ****************************************
		// Create socket & bind
		// ****************************************
		// Create UDP socket
	    sockfd = socket(AF_INET , SOCK_DGRAM , IPPROTO_UDP); //UDP packet for DNS queries
		if (sockfd < 0) {
   	      printf("ERROR opening socket.\n");
			 exit(1);
		}

		// Prepare UDP to bind port
		bzero(&servaddr,sizeof(servaddr));
		servaddr.sin_family = AF_INET;
		servaddr.sin_addr.s_addr=htonl(INADDR_ANY); 
		servaddr.sin_port=htons(port);
		
		// ****************************************
		// Receive questions
		// ****************************************

		// Bind application to UDP port
		int res = bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
		
		if(res < 0) {
	         printf("Error binding to port %d.\n", servaddr.sin_port);
			 
			 if(servaddr.sin_port <= 1024) {
				 printf("To use ports below 1024 you may need additional permitions. Try to use a port higher than 1024.\n");
			 } else {
				 printf("Please make sure this UDP port is not being used.\n");
			 }
			 exit(1);
		}


		#ifdef DEBUG
		printf("Criacao named pipe para as estatisticas\n.");
		#endif
		char* n_pipe = ptr_config->Named_pipe;
		if(verifica_ficheiros(n_pipe) == 1) {
			printf("Named pipe ja existente! A eliminar...\n");
			unlink(n_pipe);
		}
		if(((np = mkfifo(n_pipe, O_CREAT|O_EXCL|0600)<0)) && (errno != EEXIST)) {
			perror("mkfifo");
			exit(1);
		} 
		if (np != 0) {
			fprintf(stderr, "Impossivel criar fifo %s\n", n_pipe);
			return 1;
		}
		if((np = open(n_pipe, O_RDWR)) < 0) {
			perror("Opening Named Pipe");
			exit(1);
		}
	}

	#ifdef DEBUG
	printf("A sair = %d\n", getpid());
	#endif

	#ifdef DEBUG
	printf("Criacao Processo de estatisticas\n");
	#endif
	if(cfg_process != 0) {
		stats_process = fork();
		if(stats_process == 0) {
			if(signal(SIGUSR1, SIG_IGN) == SIG_ERR) {
				perror("Signal ignore error");
				exit(1);
			}
			#ifdef DEBUG
			printf("RELEASE STATS.\n");
			#endif
		} else {
			usleep(200000);
			if(signal(SIGALRM, SIG_IGN) == SIG_ERR) {
				perror("SIGALRM Ignore error");
				exit(1);
			}
		}
	}

	#ifdef DEBUG 
	printf("Quem chega primeiro = %d\n", getpid()); 
	#endif

	if(cfg_process != 0 && stats_process != 0) {
		#ifdef DEBUG
		printf("A preencher struct para argumento da funcao do thread.\n");
		#endif
		struct thread_data t_data;
		t_data.normal = fila_normal;
		t_data.prioridade = fila_prioridade;
		t_data.domains = l_domains;

		int N_THREADS = ptr_config->N_threads;

		p_threads = malloc(sizeof(*p_threads) * N_THREADS);

		#ifdef DEBUG
		printf("A criar a pool de threads.\n");
		#endif

		for(i=0;i < N_THREADS;i++) {
			pthread_create(p_threads+i, NULL, requester, (void*)&t_data);
		}
		usleep(50000);

		printf("\n\n-- Waiting for DNS message --\n\n");
	}

	while(1) {
		if((cfg_process == 0) && (ptr_config->saida == 1)) {	// MODO MANUNTENCAO
			file2memory("config.txt");
			ptr_config->saida = 0;
			usleep(100000);
			printf("\n-- Waiting for DNS message --\n");
		}
		if(cfg_process != 0 && stats_process != 0) {		// GESTOR PEDIDOS
			usleep(200000);
			
			len = sizeof(dest);

			// Thread blocking!
			if(recvfrom (sockfd, (unsigned char*)buf, 65536 , 0 , (struct sockaddr*)&dest , &len) < 0) {
				perror("Error in recvfrom");
				exit(1);
			}

			printf("DNS message received\n");

			// Process received message
			dns = (struct DNS_HEADER*) buf;
			qname = (unsigned char)buf[sizeof(struct DNS_HEADER)];
			reader = &buf[sizeof(struct DNS_HEADER)];

			// We only need to process the questions
			// We only process DNS messages with one question
			// Get the query fields according to the RFC specification
			struct QUERY query;
			if(ntohs(dns->q_count) == 1) {
				// Get NAME
				query.name = convertRFC2Name(reader,buf,&stop);
				reader = reader + stop;
				
				// Get QUESTION structure
				query.ques = (struct QUESTION*)(reader);
				reader = reader + sizeof(struct QUESTION);
				
				// Check question type. We only need to process A records.
				if(ntohs(query.ques->qtype) == 1) {
					printf("A record request.\n\n");
				} else {
					printf("NOT A record request!! Ignoring DNS message!\n");
					continue;
				}	
			} else {
				printf("\n\nDNS message must contain one question!! Ignoring DNS message!\n\n");
				continue;
			}

			#ifdef DEBUG
			printf("ID PEDIDO = %d\n", dns->id);
			#endif


			/***** VALIDAR PEDIDO *****/
			valido = 0;

			// 1. Verificar se e' localDomain (Se for, vai para a lista prioritaria)
			// TRABALHO DOS THREADS...
			if(strstr(query.name, ptr_config->localDomain) != NULL) {
				valido = 1;
				stat.pedidos_local += 1;
				insere_pedido(fila_prioridade, receber_info(query.name, &dest, dns->id, sockfd));
			} else if(ptr_config->flag % 2 == 0) {	// 2. Verificar se é um dos dominios autorizados (ptr_config->domains[])
				for(i=0; i < ptr_config->n_domains; i++) {
					if(strstr(query.name, ptr_config->domains[i]) != NULL) {
						valido = 1;
						stat.pedidos_externos += 1;
						insere_pedido(fila_normal, receber_info(query.name, &dest, dns->id, sockfd));
						break;
					}
				}
			}

			#ifdef DEBUG
			imprimir_fila(fila_normal);
			imprimir_fila(fila_prioridade);
			#endif

			if(valido == 1) {
				#ifdef DEBUG
				printf("A ENVIAR SINAL PARA A THREAD...\n");
				#endif
				pthread_cond_signal(&cond);		
			} else {	
				if(ptr_config->flag % 2 != 0) {
					printf("Durante o modo de manuntencao apenas pedidos locais sao aceites!\n");
					printf("A enviar 0.0.0.0...\n");	
				} else {
					printf("Pedido negado!\nDe momento os dominios aceites sao:\n");
					for(i=0;i<ptr_config->n_domains;i++) {
						printf("-> Dominio %d = %s\n",i,ptr_config->domains[i]);
					}
				}
				sendReply(dns->id, query.name, inet_addr("0.0.0.0"), sockfd, dest);
				printf("\n\n-- Waiting for DNS message --\n\n");
			}

			if(valido == 0) {
				stat.pedidos_negados += 1;
			}
			stat.total_pedidos += 1;

			// Enviar dados das ESTATISTICAS para o named pipe aqui
			#ifdef DEBUG
			printf("A escrever estatisticas para o named pipe\n.");
			#endif
			write(np, &stat, sizeof(struct stats));
		}
		if (stats_process == 0 && cfg_process != 0) {	// STATS Process
			signal(SIGALRM, handler_alarm);

			Config* ptr;
			if ((ptr = shmat(shmID, NULL, 0)) == (Config *) -1) {
				perror("error in shmat");
				exit(1);
			}

			struct stats st;
			char* n_pipe = ptr_config->Named_pipe;

			if((r = open(n_pipe, O_RDONLY)) < 0) {
				perror("Child open Named pipe");
				exit(1);
			}

			read(r, &st, sizeof(struct stats));
			linha(st.data_hora_arranque);

			time_t clk2 = time(NULL);
			strcpy(st.data_info, ctime(&clk2));
			linha(st.data_info);

			t_p = st.total_pedidos;
			p_n = st.pedidos_negados;
			p_l = st.pedidos_local;
			p_e = st.pedidos_externos;
			strcpy(d_a, st.data_hora_arranque);
			strcpy(u_i, st.data_info);

			alarm(FREQ);
		}
	}

	return 0;
}
Example #8
0
int main()
{
    time_t hora;
    struct tm *timeinfo;
    int Nvoos;
    int Ndecolagens;
    int Npousos;
    
    char codigo_voo[7];
    char tipo_voo;
    int combustivel_voo;
    int aviso_voo;
    int pista_voo = 1;
    
    char codigos[64][7] = {"VG3001", "JJ4404", "LN7001", "TG1501",
    "GL7602", "TT1010", "AZ1009", "AZ1008", "AZ1010", "TG1506", "VG3002", "JJ4402", "GL7603",
    "RL7880", "AL0012", "TT4544", "TG1505", "VG3003", "JJ4403", "JJ4401", "LN7002", "AZ1002",
    "AZ1007", "GL7604", "AZ1006", "TG1503", "AZ1003", "JJ4403", "AZ1001", "LN7003", "AZ1004",
    "TG1504", "AZ1005", "TG1502", "GL7601", "TT4500", "RL7801", "JJ4410", "GL7607", "AL0029",
    "VV3390", "VV3392", "GF4681", "GF4690", "AZ1020", "JJ4435", "VG3010", "LF0920", "AZ1065",
    "LF0978", "RL7867", "TT4502", "GL7645", "LF0932", "JJ4434", "TG1510", "TT1020", "AZ1098",
    "BA2312", "VG3030", "BA2304", "KL5609", "KL5610", "KL5611"};
    
    srand(time(NULL));
    
    //Gerador de número de vôos, pousos e decolagens
    Nvoos = geraRand (0, 64);
    Ndecolagens = geraRand (0, Nvoos);
    Npousos = Nvoos - Ndecolagens;
    int voos = 0;
    int dec = Ndecolagens;
    int pouso = Npousos;
     
    FILA fila = cria_fila();
    
    for(voos = 1; voos <= Nvoos; voos++){
             strcpy(codigo_voo, codigos[voos]);
             
             if(pouso > 0 && dec >0){
                      if(geraRand(0,1)){
                                  tipo_voo = 'D';
                                  dec--;
                                  combustivel_voo = geraRand (24, 48);
                                  pista_voo = ((voos-1)%3)+1;
                                  }
                      else{
                           tipo_voo = 'P';
                           pouso--;
                           combustivel_voo = geraRand (0, 12);
                           
                           if (combustivel_voo == 0)
                                                   aviso_voo = 1;
                           
                           else
                                aviso_voo = 0;
                                
                           
                           pista_voo = ((voos - 1)%3) + 1;
                           if(pista_voo == 3 && tipo_voo == 'P' && aviso_voo == 0){
                                        pista_voo = ((voos)%3) + 1;
                                        }
                           }
                      }
                      
             else if (pouso == 0 && dec !=0){
                  tipo_voo = 'D';
                  dec--;
                  combustivel_voo = geraRand (24, 48);
                  pista_voo = ((voos-1)%3) + 1;
                  }
                  
             else if (pouso != 0 && dec == 0){
                  tipo_voo = 'P';
                  pouso--;
                  combustivel_voo = geraRand (0, 12);
                  
                  if (combustivel_voo == 0){
                                          aviso_voo = 1;
                                          }
                  else{
                       aviso_voo = 0;
                       }
                  
                  pista_voo = ((voos - 1)%3) + 1;
                  if(pista_voo == 3 && tipo_voo == 'P' && aviso_voo == 0){
                               pista_voo = ((voos)%3) + 1;
                               }
                  }
                  
             insere_fila(fila, codigo_voo, tipo_voo, combustivel_voo, aviso_voo, pista_voo);
             }
    
    printf ("\n              Aeroporto Internacional de Brasilia\n");
    hora = time(NULL);
    timeinfo = localtime(&hora);
    printf("                   Hora atual: %02d:%02d:%02d\n", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
    printf("                       Fila de pedidos:\n");
    printf("                          Nvoos: %d\n", Nvoos);
    printf("                       Ndecolagens: %d\n", Ndecolagens);
    printf("                         Npousos: %d\n\n", Npousos);
    printf("             Fila designada (na ordem) por pistas:\n\n");
    printf("                     ******Pista 1:******\n                           Pousos:\n\n");
    ver_fila(fila, 'P', 1);
    printf("\n                         Decolagens:\n\n");
    ver_fila(fila, 'D', 1);
    printf("\n                     ******Pista 2:******\n                           Pousos:\n\n");
    ver_fila(fila, 'P', 2);
    printf("\n                         Decolagens:\n\n");
    ver_fila(fila, 'D', 2);
    printf("\n                     ******Pista 3:******\n                           Pousos:\n\n");
    ver_fila(fila, 'P', 3);
    printf("\n                         Decolagens:\n\n");
    ver_fila(fila, 'D', 3);
    printf("\n");
     
    libera_fila (fila);
    return 0;   
}