示例#1
0
int main(int argc, char *argv[]){
 	int l, c, linha, coluna;
 	float y;
 	
 	Matriz* x;
	scanf("%d", &linha);
	scanf("%d", &coluna);
 	
	x = cria(linha, coluna);
	
	l = linhas(x);
	c = colunas(x);
	printf("\n%d\n", l);
	printf("\n%d\n", c);
	
	
	//y = acessa(x, linha, coluna);
	//printf("\n%f\n", y); //printa 0
	
	libera(x); //libera cria que é x
	
	//y = acessa(x, linha, coluna);
	//printf("\n%f\n", y); //printa o endereço de y
	
	atribui(x, linha, coluna, 10);
	
	y = acessa(x, linha, coluna); //Neste y = acessa vai ser conferido se realmente o 10 foi atribuido à matriz
	printf("\n%.2f\n", y); //printa o endereço de y depois de executar atribui. Tem que printar 10
	
	return 0;
}
示例#2
0
int main (int argc, char** argv)
{
    char palavra[TAM], letra, novo[TAM], repete = 's';
    int tamanho, erros, i, troca, vit;

    while (repete == 's')
    {
        system ("clear");

        // Inicia variaveis
        erros = troca = vit = 0;

        // Limpa memoria
        for (i=0; i<TAM; i++)
        {
            palavra[i] = '\0';
            novo[i] = '\0';
        }

        sorteia(palavra);

        tamanho = strlen(palavra);

        // Desenha traços _
        linhas(tamanho, novo);

        while ( (erros < 7) && (vit == 0) )
        {
            printf("\t\t\tJOGO da FORCA \n\n\n");

            boneco (erros);

            printf("\t%s\n\n", novo);

            printf (" Digite uma letra: ");
            scanf (" %c", &letra);

            troca = 0;
            for (i=0; i<tamanho; i++)
            {
                if (palavra[i] == letra)
                {
                    novo[i] = letra;
                    troca = 1;
                }
            }
            if (troca == 0)
                erros++;

            system ("clear");

            // Compara palavra original com a nova
            vit = 1;
            for (i=0; i<tamanho; i++)
            {
                if (novo[i] != palavra[i])
                    vit = 0;
            }
        }

        // Verifica Vitoria
        if (vit)
            printf ("\nParabens!!!");
        else
        {
            printf ("\nPerdeu kkkk\n");
            printf ("\nO certo é \"%s\"", palavra);
        }

        // Pergunta para jogar de novo
        do
        {
            system("clear");
            printf ("\nMais uma vez?: ");
            scanf (" %c", &repete);
        }
        while (( repete != 's' ) && ( repete != 'n'));

    }

    return (EXIT_SUCCESS);
}
示例#3
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;
}