Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include "header.h"
- //timelog function
- char *timelog() {
- t = time(NULL);
- Time = *localtime(&t);
- snprintf(timenow, sizeof(timenow), "\n%d:%d:%d ",Time.tm_hour, Time.tm_min, Time.tm_sec);
- return timenow;
- }
- //code - init time - takeoff time
- int create_departure(char *c, int i, int t) {
- Lista_departure novo;
- novo = (Lista_departure) malloc(sizeof(node_struct_departure));
- novo->departure = malloc(sizeof(departure_struct));
- if(novo!=NULL){
- strcpy(novo->departure->flight_code, c);
- novo->departure->initial_time = i;
- novo->departure->takeoff_time = t;
- }
- sem_wait(&semafores->insert_queue);
- departures = insert_departure(departures,novo);
- sem_post(&semafores->insert_queue);
- write_log_file("Departure introduzida na fila com sucesso!");
- return 0;
- }
- //code - init time - time to runway - init fuel
- int create_arrival(char *c, int i, int t, int f) {
- Lista_arrival novo;
- novo = (Lista_arrival) malloc(sizeof(node_struct_arrival));
- novo->arrival = malloc(sizeof(arrival_struct));
- if(novo!=NULL){
- strcpy(novo->arrival->flight_code, c);
- novo->arrival->initial_time = i;
- novo->arrival->time_runway = t;
- novo->arrival->initial_fuel = f;
- }
- sem_wait(&semafores->insert_queue);
- arrivals = insert_arrival(arrivals, novo);
- sem_post(&semafores->insert_queue);
- write_log_file("Arrival introduzida na fila com sucesso!");
- return 0;
- }
- Lista_departure insert_departure(Lista_departure departures, Lista_departure novo){
- Lista_departure ant, act;
- if(departures == NULL){
- departures = novo;
- novo->next = NULL;
- return departures;
- }
- //(departures->departure->initial_time)>=(novo->departure->initial_time)
- act = departures->next;
- ant = departures;
- while((act->next!=NULL) && (act->departure->initial_time)<=(novo->departure->initial_time)){
- ant = ant->next;
- act = act->next;
- }
- novo->next = act;
- ant->next = novo;
- return departures;
- }
- Lista_arrival insert_arrival(Lista_arrival arrivals, Lista_arrival novo){
- Lista_arrival ant, act;
- if(arrivals == NULL){
- arrivals = novo;
- novo->next = NULL;
- return arrivals;
- }
- act = arrivals->next;
- ant = arrivals;
- while((act->next!=NULL) && (act->arrival->initial_time)<=(novo->arrival->initial_time)){
- ant = ant->next;
- act = act->next;
- }
- novo->next = act;
- ant->next = novo;
- return arrivals;
- }
- Lista_departure remove_departure(){
- Lista_departure no;
- Lista_departure removido;
- removido = (Lista_departure) malloc(sizeof(node_struct_departure));
- removido->departure = malloc(sizeof(departure_struct));
- if(departures == NULL){
- printf("Fila vazia.");
- }else if(departures->next == NULL){
- strcpy(removido->departure->flight_code,departures->departure->flight_code);
- removido->departure->initial_time = departures->departure->initial_time;
- removido->departure->takeoff_time = departures->departure->takeoff_time;
- free(departures);
- departures = NULL;
- }else{
- no = departures->next;
- strcpy(removido->departure->flight_code,departures->departure->flight_code);
- removido->departure->initial_time = departures->departure->initial_time;
- removido->departure->takeoff_time = departures->departure->takeoff_time;
- free(departures);
- departures=no;
- }
- return removido;
- }
- void remove_arrival(){
- Lista_arrival no;
- if(arrivals == NULL){
- printf("Fila vazia.");
- }else if(arrivals->next == NULL){
- free(arrivals);
- arrivals = NULL;
- }else{
- no = arrivals->next;
- free(arrivals);
- arrivals = no;
- }
- }
- void create_pipe(){
- unlink(PIPE_NAME);
- if ((mkfifo(PIPE_NAME, O_CREAT|O_EXCL|0600)<0) && (errno!=EEXIST)){
- perror("Cannot create pipe. ");
- exit(0);
- }
- write_log_file("Pipe created.");
- }
- void *workerthread_d(){
- Lista_departure no = remove_departure();
- message_struct_d message_d;
- message_d.mtype = 3;
- message_d.takeoff_time = no->departure->takeoff_time;
- message_d.slot = 0;
- if(msgsnd(mq_id,&message_d,sizeof(message_struct_d)-sizeof(long),0)!=0){
- perror("Error - msgsnd() of mq");
- }else{
- printf("Enviado para message queue\n");
- }
- printf("A iniciar\n");
- usleep(1000*5000);
- printf("A terminar...\n");
- pthread_exit(NULL);
- }
- void *workerthread_a(){
- Lista_arrival no = remove_arrival();
- message_struct_a message_a;
- if(no->arrival->initial_fuel > 4+no->arrival->time_runway+running_config->L)
- message_a.mtype =1;
- else
- message_a.mtype = 2;
- message_a.initial_fuel = no->departure->initial_fuel;
- message_a.time_runway = no->departure->time_runway;
- message_a.slot = 0;
- if(msgsnd(mq_id,&message_a,sizeof(message_struct_a)-sizeof(long),0)!=0){
- perror("Error - msgsnd() of mq");
- }else{
- printf("Enviado para message queue\n");
- }
- printf("A iniciar\n");
- usleep(1000*5000);
- printf("A terminar...\n");
- pthread_exit(NULL);
- }
- void *time_counter(){
- while(1){
- if((departures != NULL) && (departures->departure->initial_time) == mem->t){
- pthread_create(&id_thread,NULL,workerthread_d,NULL);
- }
- if((arrivals != NULL) && (arrivals->arrival->initial_time) == mem->t){
- pthread_create(&id_thread,NULL,workerthread_d,NULL);
- }
- usleep(1000*running_config->ut);
- sem_wait(&semafores->mem);
- mem->t++;
- sem_post(&semafores->mem);
- printf("Tempo %d\n",mem->t);
- }
- }
- int init_shm_mem(){
- if((mem_shmid= shmget(IPC_PRIVATE, sizeof(mem_struct*), IPC_CREAT|0700))<0){
- perror("Error - shmget() of mem struct");
- return -1;
- }
- if((mem = (mem_struct*) shmat(mem_shmid, NULL, 0)) == (mem_struct*)-1){
- perror("Error - shmat() of mem struct");
- return -1;
- }
- mem->t = 0;
- return 0;
- }
- int init_shm_stats(){
- if((stats_shmid = shmget(IPC_PRIVATE, sizeof(stats_struct*), IPC_CREAT|0700))<0){
- perror("Error - shmget() of statistics struct");
- return -1;
- }
- if((stats = (stats_struct*) shmat(stats_shmid, NULL, 0)) == (stats_struct*)-1){
- perror("Error - shmat() of statistics struct");
- return -1;
- }
- stats->n_voos_criados=0;
- stats->n_voos_aterrados=0;
- stats->t_aterrar=0.0;
- stats->n_voos_descolados=0;
- stats->t_descolados=0.0;
- stats->n_holding_aterragem=0.0;
- stats->n_holding_urgencia=0.0;
- stats->n_voos_redirecionados=0;
- stats->voos_rejeitados=0;
- return 0;
- }
- //Create departure queue
- int create_queue(){
- if((mq_id = msgget(IPC_PRIVATE, IPC_CREAT|0700)) < 0) {
- perror("Error - msgget()");
- return -1;
- }
- else {
- write_log_file("Message Queue created.");
- }
- return 0;
- }
- void close_named_pipe(){
- close(fd);
- unlink(PIPE_NAME);
- }
- //Init queues
- int init_queues() {
- departures = NULL;
- arrivals = NULL;
- d_ord = NULL;
- a_ord = NULL;
- write_log_file("Queues ready.");
- return 0;
- }
- //Ficheiro LOG
- int init_log_file() {
- printf("Creating \"log.txt\"...\n");
- if((flog = fopen(LOG_FILE_NAME, "a+")) == NULL){
- perror("Error - fopen(\"log.txt\", \"a\")");
- return -1;
- }
- write_log_file("File \"log.txt\" created successfully.");
- return 0;
- }
- // Inicializar semáforos em memória partilhada
- // Todos os semáforos declaram-se na struct respectiva e inicializam-se aqui
- int init_shm_semafores() {
- if((sem_shmid = shmget(IPC_PRIVATE, sizeof(sem_struct*), IPC_CREAT|0700))<0){
- perror("Error - shmget() of semafores struct");
- return -1;
- }
- if((semafores = (sem_struct*) shmat(sem_shmid, NULL, 0)) == (sem_struct*)-1){
- perror("Error - shmat() of semafores struct");
- return -1;
- }
- sem_init(&semafores->write_log, 1, 1);
- sem_init(&semafores->insert_queue, 1, 1);
- sem_init(&semafores->remove_queue, 1, 1);
- sem_init(&semafores->mem,1,1);
- return 0;
- }
- // Inicializar estutura de configuração de acordo com o ficheiro respectivo
- int read_config(){
- FILE *fp;
- if(!(fp = fopen("config.txt","r"))) {
- printf("Erro ao abrir o ficheiro config.txt!\n");
- exit(0);
- }
- running_config = (config_struct*) malloc(sizeof(config_struct));
- fscanf(fp,"%d",&running_config->ut);//unidade de tempo
- fscanf(fp,"%d, %d",&running_config->T,&running_config->dt);//duracao descolagem, intervalo entre descolagem
- fscanf(fp,"%d, %d",&running_config->L,&running_config->dl);//duracao aterragem, intervalo entre aterragens
- fscanf(fp,"%d, %d",&running_config->Min,&running_config->Max); //holding duracao minima, holding duracao maxima
- fscanf(fp,"%d",&running_config->D); //quantidade maxima partidas
- fscanf(fp,"%d",&running_config->A); //quantidade maxima chegadas
- //printf("%d\n",running_config->ut);
- //printf("%d, %d\n",running_config->T,running_config->dt);
- //printf("%d, %d\n",running_config->L,running_config->dl);
- //printf("%d, %d\n",running_config->Min,running_config->Max);
- //printf("%d\n",running_config->D);
- //printf("%d\n",running_config->A);
- write_log_file("Configuration file \"config.txt\" successfully loaded.");
- return 0;
- }
- void delay(int number_of_seconds){
- int milli_seconds = 1000 * number_of_seconds;
- clock_t start_time = clock();
- while(clock() < start_time + milli_seconds)
- ;
- }
- void le_pipe(){
- if((fd = open(PIPE_NAME, O_RDWR)) < 0) {
- perror("Cannot open pipe for reading:\n");
- exit(0);
- }
- else{
- write_log_file("Open pipe for reading.");
- }
- char aux[BUFFER_SIZE];
- char str[BUFFER_SIZE];
- char all_str[50];
- char flight_code[50];
- int initial_time,takeoff_time, eta, fuel;
- while(1){
- read(fd, str, BUFFER_SIZE);
- strcpy(all_str, str);
- token = strtok(str," ");
- if(strcmp(token,"DEPARTURE")==0){
- token = strtok(NULL," ");
- if(verifica_codigo(token)==0){
- sprintf(aux, "WRONG COMMAND => %s", all_str);
- write_log_file(aux);
- strncpy(aux, "", sizeof(aux));
- continue;
- }
- strcpy(flight_code, token);
- token = strtok(NULL," ");
- token = strtok(NULL," ");
- if(verifica_inteiro(token)==0){
- sprintf(aux, "WRONG COMMAND => %s", all_str);
- write_log_file(aux);
- strncpy(aux, "", sizeof(aux));
- continue;
- }
- initial_time = atoi(token);
- token = strtok(NULL," ");
- token = strtok(NULL," ");
- if(verifica_inteiro(token)==0){
- sprintf(aux, "WRONG COMMAND => %s", all_str);
- write_log_file(aux);
- strncpy(aux, "", sizeof(aux));
- continue;
- }
- takeoff_time = atoi(token);
- sprintf(aux, "NEW COMMAND => %s", all_str);
- write_log_file(aux);
- strncpy(aux, "", sizeof(aux));
- create_departure(flight_code, initial_time, takeoff_time);
- }
- else if(strcmp(token,"ARRIVAL")==0){
- token = strtok(NULL," ");
- if(verifica_codigo(token)==0){
- sprintf(aux, "WRONG COMMAND => %s", all_str);
- write_log_file(aux);
- strncpy(aux, "", sizeof(aux));
- continue;
- }
- strcpy(flight_code, token);
- token = strtok(NULL," ");
- token = strtok(NULL," ");
- if(verifica_inteiro(token)==0){
- sprintf(aux, "WRONG COMMAND => %s", all_str);
- write_log_file(aux);
- strncpy(aux, "", sizeof(aux));
- continue;
- }
- initial_time = atoi(token);
- token = strtok(NULL," ");
- token = strtok(NULL," ");
- if(verifica_inteiro(token)==0){
- sprintf(aux, "WRONG COMMAND => %s", all_str);
- write_log_file(aux);
- strncpy(aux, "", sizeof(aux));
- continue;
- }
- eta = atoi(token);
- token = strtok(NULL," ");
- token = strtok(NULL," ");
- if(verifica_inteiro(token)==0){
- sprintf(aux, "WRONG COMMAND => %s", all_str);
- write_log_file(aux);
- strncpy(aux, "", sizeof(aux));
- continue;
- }
- fuel = atoi(token); //FUEL <eta nao da wrong command
- if(fuel<eta){
- sprintf(aux, "WRONG COMMAND => %s", all_str);
- write_log_file(aux);
- strncpy(aux, "", sizeof(aux));
- continue;
- }
- sprintf(aux, "NEW COMMAND => %s", all_str);
- write_log_file(aux);
- strncpy(aux, "", sizeof(aux));
- create_arrival(flight_code, initial_time, eta,fuel);
- printf("Flitght Code: %s \n", flight_code);
- printf("Initial Time: %d\n", initial_time);
- printf("Time to runway: %d\n", eta);
- printf("Initial Fuel: %d\n", fuel);
- }
- else{
- sprintf(aux, "WRONG COMMAND => %s", all_str);
- write_log_file(aux);
- strncpy(aux, "", sizeof(aux));
- }
- }
- }
- int verifica_codigo(char *token1){
- char token[50];
- strcpy(token, token1);
- if(token[0]=='T' && token[1]=='P'){
- for(int i=2; i<strlen(token);i++){
- if(!(isdigit(token[i])==0))
- return 1;
- }
- }
- return 0;
- }
- int verifica_inteiro(char* token1){
- char token[50];
- strcpy(token, token1);
- for(int i=0; i<strlen(token);i++){
- if(isdigit(token[i])==0)
- return 0;
- }
- return 1;
- }
- void init(){
- init_shm_semafores();
- init_log_file();
- read_config();
- init_shm_stats();
- init_shm_mem();
- create_pipe();
- create_queue();
- init_queues();
- write_log_file("PROGRAM STARTED.");
- fflush(stdout);
- }
- void stats_shm_shutdown(){
- if (shmdt(stats)==-1){ // detaching da memoria partilhada
- perror("Error at detaching");
- }
- if (shmctl(stats_shmid, IPC_RMID, NULL)==-1) { //limpar memoria partilhada
- perror("Error unmapping shared memory\n");
- }
- write_log_file("Shared memory for statistics cleaned");
- }
- void mq_shutdown(){
- if(msgctl(mq_id, IPC_RMID, NULL)==-1) {
- perror("Error destroying message queue\n");
- }
- write_log_file("Message queue for departure cleaned");
- }
- void mem_shm_shutdown(){
- if (shmdt(mem)==-1){ // detaching da memoria partilhada
- perror("Error at detaching");
- }
- if (shmctl(mem_shmid, IPC_RMID, NULL)==-1) { //limpar memoria partilhada
- perror("Error unmapping shared memory\n");
- }
- write_log_file("Shared memory for mem cleaned");
- }
- void mutexes_shutdown(){
- sem_destroy(&semafores->write_log);
- sem_destroy(&semafores->insert_queue);
- sem_destroy(&semafores->remove_queue);
- sem_destroy(&semafores->mem);
- write_log_file("Semafores cleaned");
- }
- void show_stats(){
- //Escrever estatisticas - sigusr1
- printf("\n\n-----|| ESTATISTICAS ||-----\n");
- printf("Numero total de voos criados - %d\n", stats->n_voos_criados);
- printf("Numero total de voos que aterraram - %d\n", stats->n_voos_aterrados);
- printf("Tempo medio de espera para aterrar - %f\n", stats->t_aterrar);
- printf("Numero total de voos que descolaram - %d\n", stats->n_voos_descolados);
- printf("Tempo medio de espera para descolar - %f\n", stats->t_descolados);
- printf("Numero medio de manobras de holding por voo de aterragem - %f\n", stats->n_holding_aterragem);
- printf("Numero medio de manobras de holding por voo em estado de urgencia - %f\n", stats->n_holding_urgencia);
- printf("Numero de voos redirecionados para outro aeroporto - %d\n", stats->n_voos_redirecionados);
- printf("Voos rejeitados pela Torre de Controlo - %d\n", stats->voos_rejeitados);
- }
- void shutdown(int sig){
- stats_shm_shutdown();
- mem_shm_shutdown();
- mq_shutdown();
- close_named_pipe();
- free(running_config);
- fclose(flog);
- mutexes_shutdown();
- write_log_file("PROGRAM ENDED.");
- printf("\n\n");
- exit(0);
- }
- void write_log_file(char* str){
- printf("%s%s",timelog(), str);
- fflush(stdout);
- sem_wait(&semafores->write_log);
- fprintf(flog,"%s%s",timelog(), str);
- fflush(flog);
- sem_post(&semafores->write_log);
- }
- Departures_ord insert_departure_ord(message_struct_d departure){
- Departures_ord novo;
- novo = (Departures_ord) malloc(sizeof(node_struct_departure_ord));
- novo->departure = malloc(sizeof(message_struct_d));
- novo->departure->takeoff_time = departure.takeoff_time;
- Departures_ord ant, act;
- if(d_ord == NULL){
- d_ord = novo;
- novo->next = NULL;
- return d_ord;
- }
- act = d_ord->next;
- ant = d_ord;
- while((act->next!=NULL) && (act->departure->takeoff_time)<=(novo->departure->takeoff_time)){
- ant = ant->next;
- act = act->next;
- }
- novo->next = act;
- ant->next = novo;
- return d_ord;
- }
- Arrivals_ord insert_arrival_ord(message_struct_a *arrival){
- Arrivals_ord novo;
- novo = (Arrivals_ord) malloc(sizeof(node_struct_arrival_ord));
- novo->arrival = malloc(sizeof(message_struct_a));
- novo->arrival = arrival;
- Arrivals_ord ant, act;
- if(a_ord == NULL){
- a_ord = novo;
- novo->next = NULL;
- return a_ord;
- }
- while((act->next!=NULL) && (act->arrival->time_runway)<=(novo->arrival->time_runway)){
- ant = ant->next;
- act = act->next;
- }
- novo->next = act;
- ant->next = novo;
- return a_ord;
- }
- void *waiting_message_d(){
- message_struct_d message_d;
- while(1){
- if(msgrcv(mq_id, &message_d, sizeof(message_struct_d)-sizeof(long), 3, 0) >0){
- printf("ahahhhhhhhh %d\n",message_d.takeoff_time);
- d_ord = insert_departure_ord(message_d);
- }
- }
- }
- void *waiting_message_a(){
- message_a = (message_struct_a*) malloc(sizeof(message_struct_a));
- while(1){
- msgrcv(mq_id, &message_a, sizeof(message_a), -1, IPC_NOWAIT);
- a_ord = insert_arrival_ord(message_a);
- }
- }
- void torre_de_controlo(){
- char res[100];
- sprintf(res,"[%d] Torre de controlo ativa.",getpid());
- write_log_file(res);
- pthread_create(&thread_receive_d,NULL,waiting_message_d,NULL);
- pthread_create(&thread_receive_a,NULL,waiting_message_a,NULL);
- pthread_join(thread_receive_d,NULL);
- pthread_join(thread_receive_a,NULL);
- /*if(sizeof(mem->threads_departures)>running_config ->D){
- sem_wait(&semafores->stats);
- stats->voos_rejeitados++;
- sem_post(&semafores->stats);
- //terminar thread
- write_log_file("Voo rejeitado. Numero maximo atingido.");
- }*/
- }
- int main(){
- signal(SIGINT, shutdown);
- signal(SIGUSR1, show_stats);
- init();
- pid_t id = fork();
- if(id == 0){
- torre_de_controlo();
- exit(0);
- }
- else if(id == -1){
- write_log_file("Erro na criacao da torre de controlo.");
- exit(0);
- }
- else{
- pthread_create(&thread_time,NULL,time_counter,&id);
- le_pipe();
- exit(0);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement