AULA 24 - Programação 1 - Graduação

De MediaWiki do Campus São José
Ir para navegação Ir para pesquisar

Objetivos

  • Representando o tempo em uma forma apropriada para comparação de hora, minuto e segundo;
  • Uso de signal para execução periódica de handlers.

Representando o tempo em uma forma apropriada para comparação de hora, minuto e segundo

#include <stdio.h>
#include <time.h>

main()
{

   time_t rawtime; 
	struct tm *tminfo; 

   time ( &rawtime ); 
   tminfo = localtime ( &rawtime ); 
   printf ( "hora: %d minuto: %d segundo: %d \n", tminfo->tm_hour, tminfo->tm_min, tminfo->tm_sec); 
}
Exemplo
Aplicação no projeto:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
 
 
typedef struct tipo_sala{
  int  salaId;
  int  hora_ent;
  int  hora_sai;
} TSala;
 
 
main()
{
   time_t rawtime; 
   struct tm *tminfo; 
   TSala Lab1;
 
   TSala *pSala;
 
   pSala = malloc(sizeof(TSala));
 
   pSala->salaId = 5;
   pSala->hora_ent = 10;   
   pSala->hora_sai = 12; 
 
 
   /* Ler o tempo real no momento */
 
   time ( &rawtime ); 
   tminfo = localtime ( &rawtime ); 
   printf ( "hora: %d minuto: %d segundo: %d \n", tminfo->tm_hour, tminfo->tm_min, tminfo->tm_sec); 
 
   if(pSala->hora_ent <= tminfo->tm_hour && pSala->hora_sai >= tminfo->tm_hour) {
       printf("Tempo atual dentro da faixa de restrição\n");
   } else {
       printf("Tempo atual FORA da faixa de restrição \n");
   }
   free(pSala);
}


Execução Periódica de Handlers

#include <stdio.h>
#include <signal.h>
#include <sys/time.h>
#include <unistd.h>

static signal_recv_count;

void sigalrm_handler(int signum)
{
  
  signal_recv_count++;
}

void init_timer(int tempo)
{
  struct itimerval timer={0};
  char a[200];
  /* Initial timeout value */
  timer.it_value.tv_sec = tempo;

  /* We want a repetitive timer */
  timer.it_interval.tv_sec = tempo;

  /* Register Signal handler
   * And register for periodic timer with Kernel*/
  signal(SIGALRM, &sigalrm_handler);
  setitimer(ITIMER_REAL, &timer, NULL);
}

int main()
{
  init_timer(10);

  while(1) {
  		printf("imprimindo  :%d\n", signal_recv_count);
  		sleep(1);
  }
}

Decompondo string com delimitadores

#include <string.h>
#include <stdio.h>

int main()
{
   const char string_delimitada[80] = "alfa:beta:delta:epson";
   const char s[2] = ":";
   char *token;
   
   /* Ler o primeiro campo passando a string em str e o delimitador em s */
   token = strtok(string_delimitada, s);
   
   /* Ler os pŕoximos campos - passar primeiro parâmetro NULL */
   while( token != NULL ) 
   {
      printf( " %s\n", token );
    
      token = strtok(NULL, s);
   }
   
   return(0);
}


<< Aula 24 >>