Advertisement
Guest User

Untitled

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