Advertisement
Guest User

Untitled

a guest
Dec 5th, 2019
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 32.76 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <pthread.h>
  4. #include <semaphore.h>
  5. #include <sys/fcntl.h>
  6. #include <unistd.h>
  7. #include <sys/types.h>
  8. #include <sys/ipc.h>
  9. #include <sys/shm.h>
  10. #include <sys/wait.h>
  11. #include <string.h>
  12. #include <time.h>
  13. #include <assert.h>
  14. #include <sys/stat.h>
  15. #include <fcntl.h>
  16. #include <errno.h>
  17. #include <sys/msg.h>
  18. #include <signal.h>
  19.  
  20. #define DEBUG
  21. #define MAX 1024
  22. #define MAX2 50
  23. #define PIPE_NAME "input_pipe"
  24.  
  25. /****************************ESTRUTURAS********************/
  26.  
  27. typedef struct Voo_partida *lista_voo_partida;
  28. typedef struct Voo_chegada *lista_voo_chegada;
  29. typedef struct Voo_aux *lista_voos;
  30.  
  31.  
  32. typedef struct Voo{
  33. char nome[MAX2];
  34. int inicial;
  35. }voo;
  36.  
  37. typedef struct Voo_aux{
  38. char nome[MAX2];
  39. int inicial;
  40. lista_voos next;
  41. }voo_aux;
  42.  
  43. typedef struct Mensagem{
  44. long msgtyp;
  45. char nome[MAX2];
  46. int combustivel;
  47. int instante_partida;
  48. int eta;
  49. int init;
  50. int flag_prioridade;
  51. } mensagem;
  52.  
  53. typedef struct Callback_id{
  54. long msgtyp;
  55. int id;
  56. } callback_id;
  57.  
  58. typedef struct Voo_partida{
  59. voo dep;
  60. int descolagem;
  61. lista_voo_partida next;
  62. }voo_partida;
  63.  
  64. typedef struct Voo_chegada{
  65. voo arr;
  66. int eta;
  67. int combustivel;
  68. lista_voo_chegada next;
  69. }voo_chegada;
  70.  
  71. typedef struct Estatistica{
  72. int total_voos_criados;
  73. int total_voos_aterraram;
  74. time_t tempo_medio_espera_aterrar;
  75. int total_voos_descolaram;
  76. time_t tempo_medio_espera_descolar;
  77. int media_manobras_aterragem;
  78. int media_manobras_emergencia;
  79. int voos_redirecionados;
  80. int voos_rejeitados;
  81. }estatistica;
  82.  
  83. /*********************HEADER DE FUNCOES**********************/
  84.  
  85. void criar_processo_torre();
  86. char * horas();
  87. void escreve_log();
  88. void ler_config();
  89. void cria_semaforos();
  90. void cria_pipe();
  91. void cria_mq();
  92. void cria_shm_stats();
  93. void cria_shm_partida();
  94. void cria_shm_chegada();
  95. void *abre_pipe();
  96. void gestor();
  97. void *thread_manage();
  98. void *thread_worker(void* i);
  99. int condition();
  100. void imprime_lista_chegada(lista_voo_chegada head);
  101. lista_voo_partida cria_lista_partida();
  102. lista_voo_chegada cria_lista_chegada();
  103. lista_voos cria_lista_voos();
  104. void insere_lista_chegada(lista_voo_chegada head, char * n, int init, int eta, int fuel);
  105. void insere_fila_chegada(lista_voo_chegada head, char * n, int init, int eta, int fuel);
  106. void insere_lista_partida(lista_voo_partida head, char * n, int init, int desc);
  107. void insere_fila_partida(lista_voo_partida head, char * n, int init, int desc);
  108. void procura_lista_partida(lista_voo_partida lista, int chave, lista_voo_partida *ant, lista_voo_partida *atual);
  109. void procura_fila_partida(lista_voo_partida lista, int chave, lista_voo_partida *ant, lista_voo_partida *atual);
  110. void procura_lista_chegada(lista_voo_chegada lista, int chave, lista_voo_chegada *ant, lista_voo_chegada *atual);
  111. void procura_fila_chegada(lista_voo_chegada lista, int chave, lista_voo_chegada *ant, lista_voo_chegada *atual);
  112. void remove_lista_partida(lista_voo_partida partida, char *nome);
  113. void remove_lista_chegada(lista_voo_chegada chegada, char *nome);
  114. void imprime_lista_partida(lista_voo_partida teste);
  115. void insere_lista_voos(lista_voos head, char * n, int init);
  116. void procura_lista_voos(lista_voos lista, int chave, lista_voos *ant, lista_voos *atual);
  117. int hora_ut();
  118. int checkNome(lista_voos lista,char *nome);
  119. int checkLista(lista_voo_chegada chegadas, lista_voo_partida partidas,char *nome);
  120. double calcula_init(int init);
  121. void ms2ts( struct timespec *ts, unsigned long ms);
  122. void termina_programa(int signum);
  123. void remove_lista_voo(lista_voos voo, char *nome);
  124. /***********************VARIAVEIS GLOBAIS********************/
  125.  
  126. int ut_inicial; //variavel que guarda a hora inicial do sistema em segundos
  127. int ut_atual;
  128. pid_t pid_torre; //pid do processo da Torre de Controle
  129. FILE* flog; //ficheiro de log
  130. sem_t *log_mutex; //mutex do log
  131. int shm_stats_id,shm_partida_id, shm_chegad_id, mq_id,pipe_id; //variaveis de shm
  132. estatistica * stats;
  133. voo_chegada *shm_chegada;
  134. voo_partida *shm_partida;
  135.  
  136. pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
  137. pthread_mutex_t mutex_thread = PTHREAD_MUTEX_INITIALIZER;
  138.  
  139. int ut,dur_descolagem,dur_aterragem,int_descolagem,int_aterragem, holding_min, holding_max, max_partidas, max_chegadas; //variaveis de leitura da config
  140. pthread_t thread_voo[MAX2],thread_pipe, thread_manage_id;
  141.  
  142. lista_voo_chegada fila_espera_chegada;
  143. lista_voo_partida fila_espera_partida;
  144.  
  145.  
  146. lista_voo_chegada lista_chegada;
  147. lista_voo_partida lista_partida;
  148. lista_voos lista_voo_aux;
  149.  
  150. double time_to_wait;
  151. unsigned long value;
  152. struct timespec ts;
  153. int ids = 1;
  154.  
  155. /****************************FUNCOES*****************************/
  156.  
  157. //funcao para debug print
  158. void debug_print(char * aux){
  159. #ifdef DEBUG
  160. printf("[DEBUG] %s\n",aux);
  161. #endif
  162. }
  163.  
  164.  
  165. void criar_processo_torre(){
  166. debug_print("Processo Torre criado");
  167. int i;
  168.  
  169. fila_espera_partida = cria_lista_partida();
  170. fila_espera_chegada = cria_lista_chegada();
  171.  
  172. //inicializa as filas de espera a 0
  173. while(1){
  174. // fica à espera de mensagens das threads
  175. mensagem msg;
  176. callback_id index_number;
  177.  
  178. msgrcv(mq_id, &msg, sizeof(msg)-sizeof(long), -2, 0); // nº negativo funciona por prioridades -> 1º valor <= msgtype
  179.  
  180. if(msg.msgtyp == 3){
  181.  
  182.  
  183. printf("--------TORRE DE CONTROLO--------\n\n");
  184.  
  185. printf("NAME: %s \n",msg.nome);
  186. printf("TAKEOFF: %d \n",msg.instante_partida);
  187. printf("----------------\n");
  188. i = 0;
  189.  
  190. while(strcmp(shm_partida[i].dep.nome,"\0") != 0){
  191. i++;
  192. }
  193.  
  194. printf("%d\n", i);
  195.  
  196. strcpy(shm_partida[i].dep.nome,msg.nome);
  197. shm_partida[i].descolagem = msg.instante_partida;
  198. shm_partida[i].dep.inicial = msg.init;
  199.  
  200. index_number.msgtyp = 4;
  201. index_number.id = i;
  202.  
  203. insere_fila_partida(fila_espera_partida,msg.nome,msg.init,msg.instante_partida);
  204. imprime_lista_partida(fila_espera_partida);
  205. msgsnd(mq_id, &index_number, sizeof(index_number)-sizeof(long), 0);
  206. //signal(SIGINT,termina_programa);
  207.  
  208. //falta o id
  209. }
  210. else if(msg.msgtyp == 4){
  211. i=0;
  212. printf("--------TORRE DE CONTROLO--------\n\n");
  213.  
  214.  
  215. //adiciona o novo elemento à shm memory e envia o id para a thread
  216. while (strcmp(shm_chegada[i].arr.nome,"\0") != 0)
  217. {
  218. i++;
  219. }
  220. strcpy(shm_chegada[i].arr.nome,msg.nome);
  221. shm_chegada[i].arr.inicial = msg.init;
  222. shm_chegada[i].eta = msg.eta;
  223. shm_chegada[i].combustivel = msg.combustivel;
  224.  
  225. index_number.msgtyp = 1;
  226. index_number.id = i;
  227. insere_fila_chegada(fila_espera_chegada,msg.nome,msg.init, msg.eta,msg.combustivel);
  228. //falta o id
  229. imprime_lista_chegada(fila_espera_chegada);
  230. msgsnd(mq_id, &index_number, sizeof(index_number)-sizeof(long), 0);
  231. //adiciona o novo elemento a lista de espera e ordena-o
  232. //signal(SIGINT,termina_programa);
  233.  
  234. }
  235. else if(msg.msgtyp <= 2){
  236. i=0;
  237. printf("--------TORRE DE CONTROLO--------\n\n");
  238.  
  239. printf("---PRIORITY FLIGHT---\n\n");
  240.  
  241. //adiciona o novo elemento à shm memory e envia o id para a thread
  242. while (strcmp(shm_chegada[i].arr.nome,"\0") != 0)
  243. {
  244. i++;
  245. }
  246. strcpy(shm_chegada[i].arr.nome,msg.nome);
  247. shm_chegada[i].arr.inicial = msg.init;
  248. shm_chegada[i].eta = msg.eta;
  249. shm_chegada[i].combustivel = msg.combustivel;
  250.  
  251. index_number.msgtyp = 1;
  252. index_number.id = i;
  253. insere_fila_chegada(fila_espera_chegada,msg.nome,msg.init, msg.eta,msg.combustivel);
  254. //falta o id
  255. imprime_lista_chegada(fila_espera_chegada);
  256. msgsnd(mq_id, &index_number, sizeof(index_number)-sizeof(long), 0);
  257. //adiciona o novo elemento a lista de espera e ordena-o
  258. //signal(SIGINT,termina_programa);
  259.  
  260. }
  261. }
  262. }
  263.  
  264. void termina_programa(int signum){
  265.  
  266. signal(SIGINT, termina_programa);
  267. signal(SIGUSR1,SIG_IGN);
  268.  
  269. int i;
  270. i = 0;
  271. kill(pid_torre,0); //vai esperar pelo Torre de controlo acabar
  272.  
  273. escreve_log("Torre de Controlo eliminada\n");
  274. while (i < max_chegadas){ //Vai enviar sinal aos armazens para morrerem
  275. shmdt(shm_chegada);
  276.  
  277. }
  278. shmctl(shm_chegad_id,IPC_RMID,NULL);
  279.  
  280. i = 0;
  281. while (i < max_partidas){ //Vai enviar sinal aos armazens para morrerem
  282. shmdt(shm_partida);
  283.  
  284. }
  285. shmctl(shm_partida_id,IPC_RMID,NULL);
  286. lista_voo_chegada temp_c;
  287. lista_voo_partida temp_p;
  288. lista_voos temp_a;
  289. while(lista_chegada->next!=NULL){
  290. temp_c=lista_chegada;
  291. lista_chegada=lista_chegada->next;
  292. free(temp_c);
  293. }
  294. while(lista_partida->next!=NULL){
  295. temp_p=lista_partida;
  296. lista_partida=lista_partida->next;
  297. free(temp_p);
  298. }
  299.  
  300. while(lista_voo_aux->next!=NULL){
  301. temp_a=lista_voo_aux;
  302. lista_voo_aux=lista_voo_aux->next;
  303. free(temp_a);
  304. }
  305.  
  306. msgctl(mq_id, IPC_RMID, 0);
  307. escreve_log("Message queue eliminada\n");
  308. pthread_join(thread_voo,NULL);
  309. pthread_join(thread_pipe,NULL);
  310. close(pipe_id);
  311. unlink(PIPE_NAME);
  312.  
  313. pthread_mutex_destroy(&mutex_thread);
  314. pthread_cond_destroy(&cond);
  315.  
  316. exit(0);
  317.  
  318. }
  319.  
  320. //funcao que calcula hora do sistema e returna string no formato 19:35:01
  321. char * horas(){
  322. char * aux;
  323. aux = malloc(sizeof(char*));
  324. time_t atual;
  325. time(&atual);
  326. struct tm *hora_local = localtime(&atual);
  327. sprintf(aux, "%02d:%02d:%02d", hora_local->tm_hour, hora_local->tm_min, hora_local->tm_sec);
  328. return aux;
  329. }
  330.  
  331. //funcao que guarda hora de inicio do programa, em segundos
  332. void hora_inicio(){
  333. int hora_incial,minutos_inicial,segundos_inicial;
  334. time_t atual;
  335. time(&atual);
  336. struct tm *hora_local = localtime(&atual);
  337. hora_incial= hora_local->tm_hour * 60 * 60;
  338. minutos_inicial= hora_local->tm_min * 60;
  339. segundos_inicial= hora_local->tm_sec;
  340. ut_inicial = hora_incial + minutos_inicial + segundos_inicial;
  341. }
  342.  
  343. //funcao que devolve hora atual do programa em ut
  344. int hora_ut(){
  345. double aux,aux2;
  346. time_t atual;
  347. time(&atual);
  348. struct tm *hora_local = localtime(&atual);
  349. aux = (((hora_local->tm_hour * 60 * 60) + (hora_local->tm_min * 60) + hora_local->tm_sec)-ut_inicial);
  350. aux2 = (int) aux*ut/1000;
  351. return(aux2);
  352. }
  353.  
  354. double calcula_init(int init){
  355. double final,aux;
  356. int var;
  357. var = init;
  358. aux = (double) ut;
  359. var = init-hora_ut();
  360. final = (aux/1000) * var;
  361. return final;
  362. }
  363.  
  364.  
  365.  
  366. void imprime_lista_partida(lista_voo_partida head){
  367. lista_voo_partida atual = head->next;
  368. printf("LISTA DE ESPERA - VOOS PARTIDA\n");
  369. while (atual != NULL) {
  370. printf("----------------\n");
  371. printf("NOME: %s \n", atual->dep.nome);
  372. printf("Takeoff : %d\n ", atual->descolagem);
  373. printf("----------------\n");
  374. atual = atual->next;
  375.  
  376. }
  377. }
  378.  
  379. void imprime_lista_voos(lista_voos head){
  380. lista_voos atual = head->next;
  381. printf("LISTA DE VOOS\n");
  382. while (atual != NULL) {
  383. printf("----------------\n");
  384. printf("NAME: %s \n",atual->nome);
  385. printf("INIT: %d \n",atual->inicial);
  386. printf("----------------\n");
  387. printf("\n\n");
  388. atual = atual->next;
  389. }
  390. }
  391.  
  392.  
  393. void imprime_lista_chegada(lista_voo_chegada head){
  394. lista_voo_chegada atual = head->next;;
  395. printf("LISTA DE ESPERA - VOOS CHEGADA\n");
  396. while (atual != NULL) {
  397. printf("----------------\n");
  398. printf("NOME:%s\n", atual->arr.nome);
  399. printf("INIT :%d\n", atual->arr.inicial);
  400. printf("FUEL: %d \n",atual->combustivel);
  401. printf("ETA: %d\n",atual->eta);
  402. printf("----------------\n");
  403. atual = atual->next;
  404. }
  405. }
  406.  
  407.  
  408. lista_voos cria_lista_voos(){
  409. lista_voos head = NULL;
  410. head = malloc(sizeof(lista_voos));
  411. if(head != NULL){
  412. strcpy(head->nome," ");
  413. head->inicial = 0;
  414. head->next = NULL;
  415. }
  416. return(head);
  417. }
  418.  
  419.  
  420. lista_voo_partida cria_lista_partida(){
  421. lista_voo_partida head = NULL;
  422. head = malloc(sizeof(lista_voo_partida));
  423. if(head != NULL){
  424. strcpy(head->dep.nome," ");
  425. head->dep.inicial = 0;
  426. head->descolagem = 0;
  427. head->next = NULL;
  428. }
  429. return(head);
  430. }
  431.  
  432. lista_voo_chegada cria_lista_chegada(){
  433. lista_voo_chegada head = NULL;
  434. head = malloc(sizeof(lista_voo_chegada));
  435. if(head != NULL){
  436. strcpy(head->arr.nome," ");
  437. head->arr.inicial = 0;
  438. head->eta = 0;
  439. head->combustivel = 0;
  440. head->next = NULL;
  441. }
  442. return (head);
  443. }
  444.  
  445.  
  446. void insere_lista_voos(lista_voos head, char * n, int init){
  447. lista_voos atual;
  448. lista_voos ant, inutil;
  449. atual = (lista_voos) malloc (sizeof (voo_aux));
  450. if (atual != NULL)
  451. {
  452. strcpy(atual->nome,n);
  453. atual->inicial = init;
  454.  
  455. procura_lista_voos(head, init, &ant, &inutil);
  456. atual->next = ant->next;
  457. ant->next = atual;
  458. }
  459. }
  460.  
  461. void insere_lista_partida(lista_voo_partida head, char * n, int init, int desc){
  462. lista_voo_partida atual;
  463. lista_voo_partida ant, inutil;
  464. atual = (lista_voo_partida) malloc (sizeof (voo_partida));
  465. if (atual != NULL)
  466. {
  467. strcpy(atual->dep.nome,n);
  468. atual->dep.inicial = init;
  469. atual->descolagem = desc;
  470.  
  471. procura_lista_partida(head, init, &ant, &inutil);
  472. atual->next = ant->next;
  473. ant->next = atual;
  474. }
  475. }
  476.  
  477.  
  478.  
  479. void insere_fila_partida(lista_voo_partida head, char * n, int init, int desc){
  480. lista_voo_partida atual;
  481. lista_voo_partida ant, inutil;
  482. atual = (lista_voo_partida) malloc (sizeof (voo_partida));
  483. if (atual != NULL)
  484. {
  485. strcpy(atual->dep.nome,n);
  486. atual->dep.inicial = init;
  487. atual->descolagem = desc;
  488.  
  489. procura_fila_partida(head, desc, &ant, &inutil);
  490. atual->next = ant->next;
  491. ant->next = atual;
  492. }
  493. }
  494.  
  495.  
  496. int checkNome(lista_voos lista,char *nome){
  497. lista_voos atual;
  498. atual = lista->next;
  499. if(atual == NULL){
  500. return 0;
  501. }
  502. else{
  503. while(atual->next != NULL){
  504. if(strcmp(atual->nome,nome) == 0){
  505. return 1;
  506. }
  507. atual = atual->next;
  508. }
  509. return 0;
  510. }
  511. }
  512.  
  513.  
  514. void procura_lista_voos(lista_voos lista, int chave, lista_voos *ant, lista_voos *atual)
  515. {
  516. *ant = lista;
  517. *atual = lista->next;
  518. while ((*atual) != NULL &&( ((*atual)->inicial) < chave))
  519. {
  520. *ant = *atual;
  521. *atual = (*atual) -> next;
  522. }
  523. }
  524.  
  525.  
  526. void procura_lista_partida(lista_voo_partida lista, int chave, lista_voo_partida *ant, lista_voo_partida *atual)
  527. {
  528. *ant = lista;
  529. *atual = lista->next;
  530. while ((*atual) != NULL &&( ((*atual)->dep.inicial) < chave))
  531. {
  532. *ant = *atual;
  533. *atual = (*atual) -> next;
  534. }
  535. }
  536.  
  537. void procura_fila_partida(lista_voo_partida lista, int chave, lista_voo_partida *ant, lista_voo_partida *atual)
  538. {
  539. *ant = lista;
  540. *atual = lista->next;
  541. while ((*atual) != NULL &&( ((*atual)->descolagem) < chave))
  542. {
  543. *ant = *atual;
  544. *atual = (*atual) -> next;
  545. }
  546. }
  547.  
  548.  
  549. void insere_lista_chegada(lista_voo_chegada head, char * n, int init, int eta, int fuel){
  550. lista_voo_chegada atual;
  551. lista_voo_chegada ant, inutil;
  552. atual = (lista_voo_chegada) malloc (sizeof (voo_chegada));
  553. if (atual != NULL)
  554. {
  555. strcpy(atual->arr.nome,n);
  556. atual->arr.inicial = init;
  557. atual->eta = eta;
  558. atual->combustivel = fuel;
  559. }
  560.  
  561. procura_lista_chegada(head, init, &ant, &inutil);
  562. atual->next = ant->next;
  563. ant->next = atual;
  564. }
  565.  
  566.  
  567. void insere_fila_chegada(lista_voo_chegada head, char * n, int init, int eta, int fuel){
  568. lista_voo_chegada atual;
  569. lista_voo_chegada ant, inutil;
  570. atual = (lista_voo_chegada) malloc (sizeof (voo_chegada));
  571. if (atual != NULL)
  572. {
  573. strcpy(atual->arr.nome,n);
  574. atual->arr.inicial = init;
  575. atual->eta = eta;
  576. atual->combustivel = fuel;
  577. }
  578.  
  579. procura_fila_chegada(head, eta, &ant, &inutil);
  580. atual->next = ant->next;
  581. ant->next = atual;
  582. }
  583.  
  584. void procura_fila_chegada(lista_voo_chegada lista, int chave, lista_voo_chegada *ant, lista_voo_chegada *atual)
  585. {
  586. *ant = lista;
  587. *atual = lista->next;
  588. while ((*atual) != NULL && ((*atual)->eta) < chave)
  589. {
  590. *ant = *atual;
  591. *atual = (*atual) -> next;
  592. }
  593. }
  594.  
  595.  
  596.  
  597. void procura_lista_chegada(lista_voo_chegada lista, int chave, lista_voo_chegada *ant, lista_voo_chegada *atual)
  598. {
  599. *ant = lista;
  600. *atual = lista->next;
  601. while ((*atual) != NULL &&( ((*atual)->arr.inicial) < chave))
  602. {
  603. *ant = *atual;
  604. *atual = (*atual) -> next;
  605. }
  606. }
  607.  
  608.  
  609. //funcao de escrita no log
  610. void escreve_log(char *aux){
  611. sem_wait(log_mutex);
  612. fprintf(flog,"%s %s\n",horas(),aux);
  613. sem_post(log_mutex);
  614. fflush(0);
  615. }
  616.  
  617. //Funcao de leitura da config inicial do programa
  618. void ler_config(){
  619. FILE * fconfig;
  620. int linha=0;
  621. char buffer1[MAX2],buffer2[MAX2];
  622.  
  623. if ((fconfig=fopen("config.txt", "r")) == NULL){
  624. perror("Erro ao abrir o ficheiro config\n");
  625. exit(1);
  626. }else{
  627. while (linha!=6){
  628. linha++;
  629. if(linha==1){
  630. fscanf(fconfig, "%s", buffer1);
  631. ut = atoi(buffer1);
  632. }else if(linha==2){
  633. fscanf(fconfig, "%[^,],%s", buffer1,buffer2);
  634. dur_descolagem = atoi(buffer1);
  635. int_descolagem = atoi(buffer2);
  636. }else if(linha==3){
  637. fscanf(fconfig, "%[^,],%s", buffer1,buffer2);
  638. dur_aterragem = atoi(buffer1);
  639. int_aterragem = atoi(buffer2);
  640. }else if(linha==4){
  641. fscanf(fconfig, "%[^,],%s", buffer1,buffer2);
  642. holding_min = atoi(buffer1);
  643. holding_max = atoi(buffer2);
  644. }else if(linha==5){
  645. fscanf(fconfig, "%s", buffer1);
  646. max_partidas = atoi(buffer1);
  647. }else if(linha==6){
  648. fscanf(fconfig, "%s", buffer1);
  649. max_chegadas = atoi(buffer1);
  650. }
  651. }
  652. fclose(fconfig);
  653. debug_print("Ficheiro cfg lido");
  654. }
  655. }
  656.  
  657. //------------------Shared Memory Estatistica------------------------
  658. void cria_shm_stats(){
  659. if((shm_stats_id = shmget(IPC_PRIVATE,(sizeof(estatistica)),IPC_CREAT | 0766)) < 0){
  660. perror("Erro ao criar a memoria partilhada para as estatisticas ( IPC_CREAT)");
  661. }else{
  662. if(( stats = (estatistica *) shmat(shm_stats_id,NULL,0)) == (estatistica *)-1){
  663. perror("Erro ao criar a memoria partilhada para as estatisticas ( IPC_CREAT)");
  664. }
  665. else{
  666. stats->total_voos_criados = 0;
  667. stats->media_manobras_aterragem = 0;
  668. stats->total_voos_descolaram = 0;
  669. stats->total_voos_aterraram = 0;
  670. stats->media_manobras_emergencia = 0;
  671. stats->voos_redirecionados = 0;
  672. stats->voos_rejeitados = 0;
  673. stats->tempo_medio_espera_aterrar = 0;
  674. stats->tempo_medio_espera_descolar = 0;
  675. debug_print("Memoria partilhada Estatistica criada");
  676. }
  677. }
  678. }
  679.  
  680. //------------------Shared Memory Partidas------------------------
  681.  
  682. void cria_shm_partida(){
  683. if((shm_partida_id = shmget(IPC_PRIVATE,sizeof(voo_partida) * max_partidas,IPC_CREAT | 0766)) <0){
  684. perror("Erro a criar memoria partilhada para os voos de partida ");
  685. }
  686. if (( shm_partida = (voo_partida *) shmat(shm_partida_id,NULL,0)) == (voo_partida *)-1){
  687. perror("Erro a criar memoria partilhada para os voos de partida ");
  688. }
  689. else{
  690. debug_print("Memoria partilhada para os voos de partida criada com sucesso");
  691. int i;
  692. for(i = 0; i<max_partidas; i++){
  693.  
  694. strcpy(shm_partida[i].dep.nome,"\0");
  695. shm_partida[i].dep.inicial = 0;
  696. shm_partida[i].descolagem = 0;
  697. }
  698. }
  699.  
  700. }
  701. //------------------Shared Memory chegadas------------------------
  702. void cria_shm_chegada(){
  703. if((shm_chegad_id = shmget(IPC_PRIVATE,sizeof(voo_chegada) * max_chegadas,IPC_CREAT | 0766)) <0){
  704. perror("Erro a criar memoria partilhada para os voos de chegada ");
  705. }
  706. if (( shm_chegada = (voo_chegada *) shmat(shm_chegad_id,NULL,0)) == (voo_chegada *)-1){
  707. perror("Erro a criar memoria partilhada para os voos de chegada ");
  708. }
  709. else{
  710. debug_print("Memoria partilhada para os voos de chegada criada com sucesso");
  711. int i;
  712. for(i = 0; i<max_chegadas; i++){
  713.  
  714. strcpy(shm_chegada[i].arr.nome,"\0");
  715. shm_chegada[i].arr.inicial = 0;
  716. shm_chegada[i].combustivel = 0;
  717. shm_chegada[i].eta = 0;
  718. }
  719. }
  720. }
  721.  
  722. //funcao que cria pipe
  723. void cria_pipe(){
  724. unlink(PIPE_NAME);
  725. if ((mkfifo(PIPE_NAME, O_CREAT|O_EXCL|0600)<0) && (errno!= EEXIST)){ // Cria o pipe
  726. perror("Erro ao inicializar PIPE");
  727. }else{
  728. if ((pipe_id=open(PIPE_NAME, O_RDWR)) < 0){
  729. perror("Impossivel abrir Pipe para leitura");
  730. exit(0);
  731. }else{
  732. debug_print("Named Pipe criado");
  733. }
  734. }
  735. }
  736.  
  737. void *abre_pipe(){
  738. char aux[MAX],*buffer1;
  739. char auxNome[MAX2];
  740. int a,b,c;
  741. char original[MAX],erro[MAX],correto[MAX];
  742.  
  743. while (1) {
  744.  
  745. read(pipe_id, &aux, sizeof(char[MAX]));
  746. strcpy(original,aux);
  747. sprintf(correto,"%s%s","NEW COMMAND => ",original);
  748. sprintf(erro,"%s%s","WRONG COMMAND => ",original);
  749. buffer1 = strtok(aux," ");
  750.  
  751. if(strcmp(buffer1,"ARRIVAL") == 0){
  752.  
  753. //echo ARRIVAL TP437 init: 100 eta: 100 fuel: 1000 >> "input_pipe"
  754. //guarda nome
  755. buffer1 = strtok(NULL, " ");
  756. strcpy(auxNome, buffer1);
  757. //init:
  758. buffer1 = strtok(NULL, " ");
  759. if(strcmp(buffer1,"init:")!=0){
  760. escreve_log(erro);
  761. continue;
  762. }
  763. //init: 100
  764. buffer1 = strtok(NULL, " ");
  765. a = atoi(buffer1);
  766. if(a==0){
  767. escreve_log(erro);
  768. continue;
  769. }
  770. if(a<hora_ut()){
  771. escreve_log(erro);
  772. continue;
  773. }
  774. //eta:
  775. buffer1 = strtok(NULL, " ");
  776. if(strcmp(buffer1,"eta:")!=0){
  777. escreve_log(erro);
  778. continue;
  779. }
  780. //eta: 120
  781. buffer1 = strtok(NULL, " ");
  782. b = atoi(buffer1);
  783. if(b==0){
  784. escreve_log(erro);
  785. continue;
  786. }
  787. if(b<hora_ut() || b<a){
  788. escreve_log(erro);
  789. continue;
  790. }
  791. //fuel
  792. buffer1 = strtok(NULL, " ");
  793. if(strcmp(buffer1,"fuel:")!=0){
  794. escreve_log(erro);
  795. continue;
  796. }
  797. //fuel: 1000
  798. buffer1 = strtok(NULL, " ");
  799. c = atoi(buffer1);
  800. if(c==0){
  801. escreve_log(erro);
  802. continue;
  803. }
  804. if(c<b){
  805. escreve_log(erro);
  806. continue;
  807. }
  808. //pthread_mutex_unlock(&mutex_thread);
  809. pthread_mutex_lock(&mutex_thread);
  810. if((checkNome(lista_voo_aux,auxNome)== 0)){
  811. printf("O voo %s não existe no sistema, pode prosseguir\n",auxNome);
  812. insere_lista_chegada(lista_chegada,auxNome,a,b,c);
  813. insere_lista_voos(lista_voo_aux,auxNome,a);
  814. pthread_cond_signal(&cond);
  815. }
  816. else{
  817. printf("O voo %s já se encontra no sistema, acesso negado\n",auxNome);
  818. }
  819. pthread_mutex_unlock(&mutex_thread);
  820. escreve_log(correto);
  821.  
  822. }else if(strcmp(buffer1,"DEPARTURE") == 0 ){
  823. int i;
  824. //nome
  825. buffer1 = strtok(NULL, " ");
  826. strcpy(auxNome, buffer1);
  827. //init:
  828. buffer1 = strtok(NULL, " ");
  829. if(strcmp(buffer1,"init:")!=0){
  830. escreve_log(erro);
  831. continue;
  832. }
  833. //init:100
  834. buffer1 = strtok(NULL, " ");
  835. a = atoi(buffer1);
  836. if(a==0){
  837. escreve_log(erro);
  838. continue;
  839. }
  840. if(a<hora_ut()){
  841. escreve_log(erro);
  842. continue;
  843. }
  844. //takeoff:
  845. buffer1 = strtok(NULL, " ");
  846. if(strcmp(buffer1,"takeoff:")!=0){
  847. escreve_log(erro);
  848. continue;
  849. }
  850. //takeoff: 100
  851. buffer1 = strtok(NULL, " ");
  852. b = atoi(buffer1);
  853. if(b==0){
  854. escreve_log(erro);
  855. continue;
  856. }
  857. if(b<hora_ut() || b<a){
  858. escreve_log(erro);
  859. continue;
  860. }
  861. i = 0;
  862. pthread_mutex_unlock(&mutex_thread);
  863. pthread_mutex_lock(&mutex_thread);
  864. if((checkNome(lista_voo_aux,auxNome)== 0)){
  865.  
  866. printf("O voo %s não existe no sistema pode prosseguir\n",auxNome);
  867. //se o i = max_chegadas diz logo que nao dá e sai -> FAZER
  868. insere_lista_partida(lista_partida,auxNome,a,b);
  869. insere_lista_voos(lista_voo_aux,auxNome,a);
  870. pthread_mutex_unlock(&mutex_thread);
  871. pthread_cond_signal(&cond);
  872. escreve_log(correto);
  873. printf("1- check\n");
  874. }
  875. else{
  876. printf("O voo %s já se encontra no sistema, acesso negado\n",auxNome);
  877. pthread_mutex_unlock(&mutex_thread);
  878. }
  879.  
  880. }else{
  881. escreve_log(erro);
  882. }
  883. }
  884. }
  885.  
  886. //DEPARTURE TP440 init: 0 takeoff: 100 >> "input_pipe"
  887. //echo ARRIVAL TP437 init: 100 eta: 100 fuel: 1000 >> "input_pipe"
  888.  
  889. //mutex para o ficheiro de escrita no log
  890. void cria_semaforos(){
  891. sem_unlink("LOG_MUTEX");
  892. if((log_mutex = sem_open("LOG_MUTEX",O_CREAT|O_EXCL,0766,1))==SEM_FAILED){
  893. perror("Impossivel incializar o Semaforo para o Log File\n");
  894. sem_unlink("LOG_MUTEX");
  895. exit(0);
  896. }
  897. else{
  898. debug_print("Semaforos criados");
  899. }
  900. }
  901.  
  902. //--------------Message Queue------------------
  903. void cria_mq(){
  904. mq_id = msgget(IPC_PRIVATE, IPC_CREAT|0777);
  905. if (mq_id < 0)
  906. {
  907. perror("Erro ao inicializar a message queue");
  908. }
  909. else{
  910. debug_print("Message queue criada");
  911. }
  912. }
  913.  
  914. //thread voo
  915. void *thread_worker(void* i){
  916.  
  917. int id;
  918. mensagem msg;
  919. callback_id call;
  920.  
  921. int flag;
  922. flag = *((int*) i);
  923. //vai buscar o ultimo elemento da lista de voos para enviar pela mq a info
  924.  
  925. //procura na lista de voos de partida
  926.  
  927. lista_voo_chegada chegada_aux;
  928. lista_voo_partida partida_aux;
  929. debug_print("Thread Voo Criada");
  930. chegada_aux = lista_chegada;
  931. partida_aux = lista_partida;
  932.  
  933. if(flag == 2){
  934. pthread_mutex_unlock(&mutex_thread);
  935. pthread_mutex_lock(&mutex_thread);
  936. strcpy(msg.nome,partida_aux->next->dep.nome);
  937. msg.eta = 0;
  938. msg.combustivel = 0;
  939. msg.flag_prioridade = 0;
  940. msg.msgtyp = 3;
  941. msg.instante_partida = partida_aux->next->descolagem;
  942. msg.init = partida_aux->next->dep.inicial;
  943. remove_lista_voo(lista_voo_aux,lista_partida->next->dep.nome);
  944. remove_lista_partida(lista_partida,lista_partida->next->dep.nome);
  945. msgsnd(mq_id, &msg, sizeof(msg)-sizeof(long), 0);
  946. while(1){
  947. msgrcv(mq_id, &call, sizeof(call)-sizeof(long), 0, 0);
  948. id = call.id;
  949. printf("ID- %d\n", id);
  950. if(id>= 0 && id <=max_chegadas){
  951. break;
  952. }
  953. }
  954. pthread_mutex_unlock(&mutex_thread);
  955.  
  956. } //procura na lista de voos de chegada
  957. else if(flag == 1){
  958. if(chegada_aux->next->combustivel <= 4 * ut + chegada_aux->next->eta){
  959. msg.msgtyp = 1;
  960. printf("PRIORITY\n");
  961.  
  962. strcpy(msg.nome,chegada_aux->next->arr.nome);
  963. msg.eta = chegada_aux->next->eta;
  964. msg.combustivel = chegada_aux->next->combustivel;
  965. msg.init = chegada_aux->next->arr.inicial;
  966. msg.flag_prioridade = 0;
  967. msg.instante_partida = 0;
  968. remove_lista_voo(lista_voo_aux,chegada_aux->next->arr.nome);
  969. remove_lista_chegada(lista_chegada,chegada_aux->next->arr.nome);
  970.  
  971. msgsnd(mq_id, &msg, sizeof(msg)-sizeof(long), 0);
  972. while(1){
  973. msgrcv(mq_id, &call, sizeof(call)-sizeof(long), 0, 0);
  974. id = call.id;
  975. printf("ID- %d\n", id);
  976. if(id>= 0 && id <=max_chegadas){
  977. break;
  978. }
  979. }
  980. pthread_mutex_unlock(&mutex_thread);
  981. }
  982. else{
  983. pthread_mutex_unlock(&mutex_thread);
  984. pthread_mutex_lock(&mutex_thread);
  985. printf("NOT PRIORITY\n");
  986. msg.msgtyp = 4;
  987. strcpy(msg.nome,chegada_aux->next->arr.nome);
  988. msg.eta = chegada_aux->next->eta;
  989. msg.combustivel = chegada_aux->next->combustivel;
  990. msg.init = chegada_aux->next->arr.inicial;
  991. msg.flag_prioridade = 0;
  992. msg.instante_partida = 0;
  993. remove_lista_voo(lista_voo_aux,chegada_aux->next->arr.nome);
  994. remove_lista_chegada(lista_chegada,chegada_aux->next->arr.nome);
  995. msgsnd(mq_id, &msg, sizeof(msg)-sizeof(long), 0);
  996. while(1){
  997. msgrcv(mq_id, &call, sizeof(call)-sizeof(long), 0, 0);
  998. id = call.id;
  999. printf("ID- %d\n", id);
  1000. if(id>= 0 && id <=max_chegadas){
  1001. break;
  1002. }
  1003. }
  1004. pthread_mutex_unlock(&mutex_thread);
  1005. }
  1006. while (1){
  1007. if(shm_chegada[id].eta <= hora_ut()){
  1008. break;
  1009. }
  1010. }
  1011. }
  1012. }
  1013. //funcao que chama as funcoes todas de criar
  1014. void gestor(){
  1015. cria_semaforos();
  1016. ler_config();
  1017. hora_inicio();
  1018. cria_semaforos();
  1019. cria_shm_stats();
  1020. cria_shm_chegada();
  1021. cria_shm_partida();
  1022. pthread_mutex_init(&mutex_thread,NULL);
  1023. pthread_cond_init(&cond, NULL);
  1024. lista_chegada = cria_lista_chegada();
  1025. lista_partida = cria_lista_partida();
  1026. lista_voo_aux = cria_lista_voos();
  1027. cria_mq();
  1028. cria_pipe();
  1029. }
  1030.  
  1031. void remove_lista_chegada(lista_voo_chegada chegada, char *nome){
  1032. lista_voo_chegada atual,ant;
  1033. atual = chegada->next;
  1034. ant = chegada;
  1035. if(atual!= NULL){
  1036. while (strcmp(atual->arr.nome,nome)!=0)
  1037. {
  1038. atual = atual->next;
  1039. ant = ant->next;
  1040. }
  1041. ant->next = atual->next;
  1042. free(atual);
  1043. }
  1044. }
  1045.  
  1046. void remove_lista_voo(lista_voos chegada, char *nome){
  1047. lista_voos atual,ant;
  1048. atual = chegada->next;
  1049. ant = chegada;
  1050. if(atual!= NULL){
  1051. while (strcmp(atual->nome,nome)!=0)
  1052. {
  1053. atual = atual->next;
  1054. ant = ant->next;
  1055. }
  1056. ant->next = atual->next;
  1057. free(atual);
  1058. }
  1059. }
  1060.  
  1061. void remove_lista_partida(lista_voo_partida partida, char *nome){
  1062. lista_voo_partida atual,ant;
  1063. atual = partida->next;
  1064. ant = partida;
  1065. if(atual!= NULL){
  1066. while (strcmp(atual->dep.nome,nome)!=0)
  1067. {
  1068. atual = atual->next;
  1069. ant = ant->next;
  1070. }
  1071. ant->next = atual->next;
  1072. free(atual);
  1073. }
  1074. }
  1075.  
  1076. int checkLista(lista_voo_chegada chegadas, lista_voo_partida partidas,char *nome){
  1077. lista_voo_partida atual_partida;
  1078. lista_voo_chegada atual_chegada;
  1079. atual_chegada = chegadas;
  1080. atual_partida = partidas;
  1081. if(chegadas->next == NULL){
  1082. while(partidas->next != NULL){
  1083. if(strcmp(partidas->next->dep.nome,nome) == 0){
  1084. return 2;
  1085. }
  1086. else{
  1087. partidas = partidas->next;
  1088. }
  1089. }
  1090. }
  1091. else if(partidas->next == NULL){
  1092. while(chegadas->next != NULL){
  1093. if(strcmp(chegadas->next->arr.nome,nome) == 0){
  1094. return 1;
  1095. }
  1096. else{
  1097. chegadas = chegadas->next;
  1098. }
  1099. }
  1100. }
  1101. else if(partidas->next != NULL && chegadas->next != NULL){
  1102. while(chegadas->next != NULL){
  1103. if(strcmp(chegadas->next->arr.nome,nome) == 0){
  1104. return 1;
  1105. }
  1106. else{
  1107. chegadas = chegadas->next;
  1108. }
  1109. }
  1110. while(partidas->next != NULL){
  1111. if(strcmp(partidas->dep.nome,nome) == 0){
  1112. return 2;
  1113. }
  1114. else{
  1115. partidas = partidas->next;
  1116. }
  1117. }
  1118. }
  1119. }
  1120.  
  1121. int condition(){
  1122.  
  1123. double var;
  1124. var = (hora_ut());
  1125. if(lista_voo_aux->next != NULL){
  1126. if(lista_voo_aux->next->inicial <= hora_ut()){
  1127. return 1;
  1128. }
  1129. else{
  1130. return 0;
  1131. }
  1132. }
  1133. else{
  1134. return 0;
  1135. }
  1136. }
  1137.  
  1138. void *thread_manage(){
  1139.  
  1140. int k;
  1141. k=-1;
  1142.  
  1143. while(1){
  1144. pthread_mutex_lock(&mutex_thread);
  1145. while(condition() == 0){
  1146. if(lista_voo_aux->next != NULL){
  1147. printf("2- check\n");
  1148. clock_gettime(CLOCK_REALTIME, &ts);
  1149. double var;
  1150. var = calcula_init(lista_voo_aux->next->inicial);
  1151. ts.tv_sec += var;
  1152. pthread_cond_timedwait(&cond,&mutex_thread,&ts);
  1153. }
  1154. else{
  1155. clock_gettime(CLOCK_REALTIME, &ts);
  1156. ts.tv_sec += 5;
  1157. printf("ESPEROU + 5seg\n");
  1158. pthread_cond_timedwait(&cond,&mutex_thread,&ts);
  1159. }
  1160. }
  1161. k++;
  1162. int a = checkLista(lista_chegada,lista_partida,lista_voo_aux->next->nome);
  1163. remove_lista_voo(lista_voo_aux,lista_voo_aux->next->nome);
  1164. pthread_mutex_unlock(&mutex_thread);
  1165.  
  1166. if(pthread_create(&thread_voo[k],NULL,thread_worker, (void*) &a) !=0){
  1167. perror("ERROR creating the thread pipe!\n");
  1168. }
  1169. printf("Asnbasv\n");
  1170. //signal(SIGINT,termina_programa);
  1171. }
  1172.  
  1173. }
  1174.  
  1175. int main(){
  1176.  
  1177. lista_voo_chegada aux_lista_chegada;
  1178. lista_voo_partida aux_lista_partida;
  1179. lista_voos aux_lista_voos;
  1180.  
  1181. aux_lista_partida = lista_partida;
  1182. aux_lista_chegada = lista_chegada;
  1183. aux_lista_voos = lista_voo_aux;
  1184. int k;
  1185. k=-1;
  1186.  
  1187. pthread_mutex_init(&mutex_thread,NULL);
  1188. pthread_cond_init(&cond, NULL);
  1189.  
  1190. debug_print("Programa iniciado");
  1191.  
  1192. flog=fopen("log.txt","w");
  1193.  
  1194. gestor();
  1195.  
  1196. if(pthread_create(&thread_pipe,NULL,abre_pipe,NULL)!=0){
  1197. perror("ERROR creating the thread pipe!\n");
  1198. }
  1199.  
  1200. if ((pid_torre = fork()) == 0) {
  1201. criar_processo_torre();
  1202. }
  1203. else if (pid_torre == -1) {
  1204. perror("Erro a criar o processo torre de controlo");
  1205. }
  1206. else{
  1207.  
  1208. if(pthread_create(&thread_manage_id,NULL,thread_manage,NULL)!=0){
  1209. perror("ERROR creating the thread pipe!\n");
  1210. }
  1211. while(1){
  1212. sleep(10);
  1213. }
  1214. }
  1215. fclose(flog);
  1216. return 0;
  1217. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement