Advertisement
Guest User

Untitled

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