void main() { List_head lista_reservas ; List_head lista_pre_reservas ; lista_reservas = cria_lista() ; lista_pre_reservas = cria_lista() ; menu_main(lista_reservas, lista_pre_reservas) ; }
desktop *cria_desktop(void) { desktop *desk = malloc(sizeof(desktop)); if (!desk) falha_aloc(); desk->lista_caixas = cria_lista(); desk->desenha = &desenha_desktop; desk->monitora = &monitora_desktop; desk->atualiza = &atualiza_desktop; return desk; }
int main(){ int casos,k,n; scanf("%d",&casos); for(int i = 1; i <= casos; i++){ Lista *l = cria_lista(); scanf("%d",&n); insere_vitima(l,n); scanf("%d",&k); while(l->qtd != 1){ busca(l,k); } printf("Case %d: %d\n",i,l->head->num); } return 0; }
/********************************************* * Funcao principal *********************************************/ int main(){ int opcao; unsigned int id_remover; Carro carro; Lista *lista = cria_lista(); limpa_tela(); // Cria uns carros estaticos, to cansado de ficar digitando carro = cria_carro_estatico(1, "Gol", 2009, "Vermelho", 15000); add_item_lista(lista, carro); carro = cria_carro_estatico(2, "Palio", 2004, "Prata", 13000); add_item_lista(lista, carro); carro = cria_carro_estatico(3, "Strada", 2008, "Preto", 15000); add_item_lista(lista, carro); do { mostra_menu(&opcao); if(opcao > 0 && opcao < 5){ switch(opcao){ case 1: carro = cria_carro(); add_item_lista(lista, carro); break; case 2: id_remover = remove_carro(); remove_item_lista(lista, id_remover); break; case 3: imprime_lista(lista); break; } } } while(opcao != 4); libera_lista(lista); }
void gerar_grafo(int tamanho, float densidade) { int i, k, j, dest, peso, max_nodos, cont_max, max_atual; TipoLista* lista; lista = cria_lista(tamanho); max_nodos = (int)tamanho*densidade; for (i=0; i<tamanho; i++) { max_atual = max_nodos - lista->nodos[i].quantidade; for (k=0; k<max_atual; k++) { cont_max = 0; do { dest = rand()%tamanho; cont_max++; if (cont_max > tamanho) break; }while (tem_item(*lista, i, dest) || dest == i || lista->nodos[dest].quantidade == max_nodos); if (cont_max < tamanho) { peso = 10 + rand()%1000; add_item(lista, i, dest, peso); add_item(lista, dest, i, peso); } else { for (j=0; j<tamanho; j++) { if (!tem_item(*lista, i, j) && j != i && !(lista->nodos[j].quantidade == max_nodos)) { peso = 10 + rand()%1000; add_item(lista, i, j, peso); add_item(lista, j, i, peso); break; } } } } } grava_lista(*lista, lista->tamanho, max_nodos); apaga_lista(lista); }
int main () { int lin,col; int matriz [MAX_LIN][MAX_COL],mlista [MAX_LIN*MAX_COL][MAX_COL]; FILE *arq_entrada, *arq_saida; char nome_file_entrada [TAMANHO_NOME]; char nome_file_saida [TAMANHO_NOME]; printf ("*********** Programa para analise de pontos de alagamento ***********\n"); printf ("\n\t Digite o nome do arquivo de entrada : "); scanf ("%s", nome_file_entrada); printf ("\n\t Digite o nome do arquivo de saida : "); scanf ("%s",nome_file_saida); printf ("\n\t Digite a ordem da Matriz, primeiro linhas e depois colunas : "); scanf ("%d %d",&lin,&col); arq_entrada = fopen (nome_file_entrada, "r"); arq_saida = fopen (nome_file_saida, "w"); if (arq_entrada == NULL) printf ("Arquivo de entrada %s nao existe\n",nome_file_entrada); fprintf(arq_saida,"****************************************************************\n"); fprintf(arq_saida,"*** ***\n"); fprintf(arq_saida,"*** MAC0110 - Introducao a Computacao - 1o. semestre 2012 ***\n"); fprintf(arq_saida,"*** Quarto Exercício Programa (EP4) ***\n"); fprintf(arq_saida,"*** ***\n"); fprintf(arq_saida,"*** Aluno : Fellipe Souto Sampaio ***\n"); fprintf(arq_saida,"*** Numero USP : 7990422 ***\n"); fprintf(arq_saida,"*** Curso : Bacharelado Matemática ***\n"); fprintf(arq_saida,"*** ***\n"); fprintf(arq_saida,"****************************************************************\n\n\n"); cmatriz (matriz,lin,col,&*arq_entrada,&*arq_saida); cria_lista (matriz,mlista,lin,col); marcacomk (matriz,mlista); printf ("\n\n\tMatriz numerica dos pontos de alagamento\n\n"); marcamatriz (matriz,mlista); imprime_m(matriz,lin,col); imprime_ms(matriz,lin,col,&*arq_entrada,&*arq_saida); printf ("\n\n\tMatriz char dos pontos de alagamento\n\n"); marca_char (matriz,mlista); imprime_char(matriz,lin,col); imprime_chars(matriz,lin,col,&*arq_entrada,&*arq_saida); fclose (arq_entrada); fclose (arq_saida); return 0; }
pNodoA* InsereAVL (pNodoA *a, char x[], int *ok, int linha) { /* Insere nodo em uma árvore AVL, onde A representa a raiz da árvore, x, a chave a ser inserida e h a altura da árvore */ if (a == NULL) { a = (pNodoA*) malloc(sizeof(pNodoA)); strcpy(a->palavra,x); a->esq = NULL; a->dir = NULL; a->FB = 0; a->linhas = cria_lista(); *ok = 1; } if (strcmp(a->palavra,x) == 0) //Sao iguais as palavras, soma mais uma informação de que linha foi encontrada { InfoNo dados; dados.list = linha; a->linhas = insereLSE(a->linhas, dados); } else{ if (strcmp(a->palavra,x) > 0) { a->esq = InsereAVL(a->esq,x,ok,linha); if (*ok) { switch (a->FB) { case -1: a->FB = 0; *ok = 0; break; case 0: a->FB = 1; break; case 1: a=Caso1(a,ok); break; } } } if((strcmp(a->palavra,x) < 0)) { // printf("Foi pra direita -> Palavra: %s", a->palavra); a->dir = InsereAVL(a->dir,x,ok,linha); if (*ok) { switch (a->FB) { case 1: a->FB = 0; *ok = 0; break; case 0: a->FB = -1; break; case -1: a = Caso2(a,ok); break; } } } } return a; }
void caminho_curto(){ // ----------------------------------- MATRIZ ADJACENTE FILE *arq; int cont, e; arq = fopen("grafo.txt", "r"); char x = 1, atual = 0, aux; int cont2 = 0, cont3 = 1, i = 0, j = 0; cont = qtd_vertices(arq); // CRIANDO MATRIZ int mat[cont][cont]; for(i = 0; i < cont; i++){ for(j = 0; j < cont; j++){ mat[i][j] = 0; } } // CRIA LISTA E ELEMENTO AUXILIAR Lista *L = cria_lista(); ElementoL *E; // CORE fflush(stdout); fseek(arq, 2, SEEK_SET); // Posiciona cursor na segunda linha x = fgetc(arq); while(x != EOF){ while(x != '\n'){ // varre uma linha do txt // Busca Letra na Lista E = busca_letra(x, L); if (E == NULL){ adiciona_letra(L, x , cont2); cont2++; } i = get_numero(busca_letra(x, L)); // ------------- J fseek(arq, 1, SEEK_CUR); x = fgetc(arq); E = busca_letra(x, L); if(E == NULL){ adiciona_letra(L, x , cont3); cont3++; } j = get_numero(busca_letra(x, L)); // ------------- J fseek(arq, 1, SEEK_CUR); fscanf(arq, "%i", &mat[i][j]); x = fgetc(arq); // Pula uma letra } x = fgetc(arq); if(atual != x){ // mudou de linha atual = x; // recebe letra do vertice i++; } } for(i = 0; i + 1 < cont ; i++){ printf("\n"); for(j = 0; j + 1< cont; j++){ printf(" %d |",mat[i][j]); } } // ----------------------------------- char c1, c2; // LER OS VERTICES flush_in(); printf("Entre com o primeiro vértice:"); scanf("%c", &c1); flush_in(); printf("\nEntre com o segundo vértice:"); scanf("%c", &c2); // --- com fila! // printa c1 for(i = 0;i < cont;i++){ // analisa o i atual for(j = 0;j < cont;j++){ // joga coluna atual na fila } } // --- Analisa linha A /*E = busca_letra(c1, L); printf("\n %c - ", c1); for(j = 0; j < cont; j++){ if(mat[E->numero][j] != 0){ // É solução ? // printa // return // Não é solução } }*/ // ------------------- // FECHAR ARQUIVO DO GRAFO fclose(arq); }
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; }