guidabasec-blog
guidabasec-blog
Guida di base al C
68 posts
La guida ai fondamenti del C
Don't wanna be here? Send us removal request.
guidabasec-blog · 14 years ago
Text
wait child
#include "ourhdr.h"
#include <sys/types.h>
#include <sys/wait.h>
void pr_exit(int status)
{
  if (WIFEXITED(status))
    printf("normal termination, exit status = %d\n",
        WEXITSTATUS(status));
  else if (WIFSIGNALED(status))
    printf("abnormal termination, signal number = %d%s\n",
        WTERMSIG(status),
#ifdef  WCOREDUMP
        WCOREDUMP(status) ? " (core dumped)" : "");
#else
        "");
#endif
  else if (WIFSTOPPED(status))
    printf("child stopped, signal number = %d\n",
        WSTOPSIG(status));
}
int main(void)
{
pid_t pid;
int status;
if ( (pid = fork()) < 0)
perror("fork error");
else if (pid == 0) /* child */
pr_exit(7);
if (wait(&status) != pid) /* wait for child */
perror("wait error");
pr_exit(status); /* and print its status */
if ( (pid = fork()) < 0)
perror("fork error");
else if (pid == 0) /* child */
abort(); /* generates SIGABRT */
if (wait(&status) != pid) /* wait for child */
perror("wait error");
pr_exit(status); /* and print its status */
if ( (pid = fork()) < 0)
perror("fork error");
else if (pid == 0) /* child */
status /= 0; /* divide by 0 generates SIGFPE */
if (wait(&status) != pid) /* wait for child */
perror("wait error");
pr_exit(status); /* and print its status */
exit(0);
}
1 note · View note
guidabasec-blog · 14 years ago
Text
vfork exec respawn
/********************************************************************************/
/*Scrivere un programma in linguaggio C che attivi un programma e stia in attesa*/
/*se per qualche motivo il programma controllato termina lo deve lanciare       */
/*nuovamente. */
/*e.g. */
/*        respawn mydeamond -a -b -c */
/*attiva mydaemond con i parametri indicati, se mydaemond termina viene */
/*rilanciato nello stesso modo. */
/*(Hint usare wait o meglio waitpid). */
/********************************************************************************/
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
main(){
pid_t cpid,ris;
int status;
/*faccio un while true perchè nel caso il processo figlio termini lo rilancio*/
while(1)
{
/*la vfork restituisce 0 al figlio e il pid del figlio creato al padre*/
cpid = vfork();
if(cpid<0) 
{
printf("errore vfork");
exit(1);
}
if(cpid==0)
{
printf("il pid del figlio e' %ld\n",(long)getpid());
//execl("/bin/bash","/bin/bash","firefox",0);
execlp("firefox",0);
}
else
{
do
{
/*non ho messo nessun opzione, in questo caso è bloccante*/ 
/*(in attesa del segnale dal figlio)*/
ris=waitpid(cpid,&status,0);
if(ris<0)
{
printf("errore nella waitpid");
exit(1);
}
if (WIFEXITED(status)) 
{
printf("exited, status=%d\n", WEXITSTATUS(status));
else if (WIFSIGNALED(status)) 
{
printf("killed by signal %d\n", WTERMSIG(status));
}
      } while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
}
}
/*WIFEXITED(status)::ritorna true se lo status corrisponde ad un child che ha terminato normalmente*/
/*WIFSIGNALED(status)::ritorna true se lo status corrisponde ad un child che ha terminato in modo anormale*/
3 notes · View notes
guidabasec-blog · 14 years ago
Text
tombola
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
/* Numero di giocatori nel sistema */
#define NGIOCATORI 3
/* Numero di valori da estrarre */
#define MAXNUM 10
/* Numero di valori in una cartella */
#define DIMCARTELLA 4
/* File name utilizzato per comunicare */
#define FILENAME "giocata"
/* Scrive un messaggio di errore e poi termina */
void errquit(char* message)
{
  perror(message);
  exit(1);
}
/* Genera un numero casuale fra 0 e max-1 */
int casuale(int max)
{
  long int val = random();
  return val % max;
}
/* True se questo processo e' un child */
static int child = 0;
/* True se il parent ha spedito una nuova giocata */
static int nuovagiocata;
/* Numero di risposte dai child */
static int rispostemancanti;
/* Tombola! */
static int tombola;
void sig_usr1(int signo)
{
  rispostemancanti--;
}
void doparent(int* giocatori)
{
  /* Cartella di numeri estratti, mantenuta come array di booleani */
  int estratti[MAXNUM];
  /* Numero di valori ancora da estrarre */
  int daestrarre;
  /* File descriptor per il file condiviso*/
  int fd; 
  /* Maschere */
  sigset_t     newmask, oldmask, zeromask;
  /* Contatori, variabili di appoggio */
  int i, valore;
  srandom(getpid());
  /* Inizializza struttura dati */
  for (i=0; i < MAXNUM; i++)
    estratti[i] = 0;
  daestrarre = MAXNUM;
  /* Apre il file con le giocate in lettura */
  fd = open(FILENAME, O_WRONLY);
  /* Inizializza signal handling */
  signal(SIGUSR1, sig_usr1);
  sigemptyset(&newmask);
  sigaddset(&newmask, SIGUSR1);
  sigprocmask(SIG_BLOCK, &newmask, &oldmask);
  /* Main loop */
  tombola = 0;
  while (!tombola && daestrarre > 0) {
    daestrarre--;
    /* Estrai un numero che non e' gia' stato estratto */
    printf("Parent: prima dell'estrazione\n", valore);
    do {
      valore = casuale(MAXNUM);
    } while (estratti[valore]);
    estratti[valore]=1;
    /* Scrive il valore estratto */
    if (lseek(fd, SEEK_SET, 0) < 0)
      errquit("PARENT: SEEK error");
    if (write(fd, &valore, sizeof(int)) < 0)
      errquit("PARENT: WRITE error");
    /* Sveglia i giocatori */
    for (i=0; i < NGIOCATORI; i++) 
      kill(giocatori[i], SIGUSR1);
    /* Aspetta le risposte */
    sigemptyset(&zeromask);
    rispostemancanti = NGIOCATORI;
    while (rispostemancanti > 0)
      sigsuspend(&zeromask);
    printf("Parent: Ricevute tutte le risposte\n");  
  }
  valore = -1;
  if (tombola) {
    printf("Parent: Tombola!\n");
  } else {
    printf("Parent: Nessuno ha vinto\n");
  }
  /* Scrive -1 per concludere la partita */
  if (lseek(fd, SEEK_SET, 0) < 0)
    errquit("PARENT: SEEK error");
  if (write(fd, &valore, sizeof(int))<0)
    errquit("PARENT: WRITE error");
  /* sveglia tutti i giocatori */
  /* attende la terminazione dei figli */ 
}
void sig_usr1_child(int signo)
{
  nuovagiocata = 1;
}
void dochild()
{
  /* Cartella di numeri, mantenuta come array di booleani */
  int cartella[MAXNUM];
  /* Numeri mancanti alla tombola */
  int mancanti; 
  /* Maschere per gestione segnali */
  sigset_t     newmask, oldmask, zeromask;
  /* File descriptor per il file condiviso*/
  int fd; 
  /* Contatori, variabili di appoggio */
  int i, valore;
  /* Genera cartella casuale */
  srandom(getpid());
  for (i=0; i < MAXNUM; i++)
  cartella[i] = 0;
  i=0;
  while (i < DIMCARTELLA) {
    valore = casuale(MAXNUM);
    if (!cartella[valore]) {
      cartella[valore] = 1;
      i++;
    }
  }
  mancanti = DIMCARTELLA;
  /* Apre il file con le giocate in lettura */
  fd = open(FILENAME, O_RDONLY);
  /* Inizializza signal handling */ 
  signal(SIGUSR1, sig_usr1_child);
  sigemptyset(&newmask);
  sigaddset(&newmask, SIGUSR1);
  sigprocmask(SIG_BLOCK, &newmask, &oldmask);
  /* Main loop */
  while (mancanti > 0) {
    /* Aspetto una nuova giocata */
    nuovagiocata = 0;
    while (!nuovagiocata) 
      sigsuspend(&zeromask);
    /* Leggo */
    if (lseek(fd, SEEK_SET, 0) < 0)
      errquit("CHILD: SEEK error");
    if (read(fd, &valore, sizeof(int))<0)
      errquit("CHILD: READ error");
    if (valore < 0) {
      /* Se il valore e' negativo, qualcuno ha fatto tombola */
      printf("Child[%d]: fine partita\n",getpid());
      exit(0);
    }
    printf("Child[%d]: e' stato estratto %d\n",getpid(), valore);
    if (cartella[valore]) {
      printf("Child[%d]: ok!, mancano %d\n",getpid(), mancanti);
      cartella[valore] == 0;
      mancanti--;
      if (mancanti == 0) {
        printf("Child[%d]: tombola\n",getpid());
        /* Ho fatto tombola; spedisco un segnale SIGUSR2 al parent */
        kill(getppid(), SIGUSR2);
      }
    }
    /* Spedisco un segnale SIGUSR1 al parent per confermare la lettura */
    kill(getppid(), SIGUSR1);
  }
}
int main(int argc, char* argv[])
{
  /* Process id ottenuto da fork */
  int pid;
  /* Process id dei giocatori */
  int giocatori[NGIOCATORI];
  /* Counter */
  int i;
  /* Faccio il fork di NGIOCATORI figli */
  for (i=0; i < NGIOCATORI; i++) {
    pid = fork();
    if (pid > 0) {
      giocatori[i] = pid;
    } else if (pid == 0) {
      child = 1;
      break;
    }
  /* Scelgo cosa fare, a seconda che sia padre e/o figlio */
  if (child) {
    doChild();
  } else {
    doParent(giocatori);
  }
}
10 notes · View notes
guidabasec-blog · 14 years ago
Text
token ring
#include <stdio.h> 
#include <stdlib.h> 
#include <errno.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/wait.h>
#include <fcntl.h> 
#include <sys/stat.h>
#include <signal.h> 
volatile flag=0;
void handler()
{
flag=1;
}
#define TOKEN 7
void main()
{
int i,fd;
int n=3;
pid_t pid, root_pid;
root_pid=getpid();
//mkfifo("myfifo", 0700);
sigset_t newmask,oldmask;
int buf;
signal(SIGUSR1,handler);
 for (i=0; i < n; i++) {
     pid = fork();
    if (pid < 0) 
      perror("Problema con fork");
if(pid==0);
else break;
     }
  if (pid==0)
    {
    /* Siamo nel figlio */
kill(root_pid,SIGUSR1);//il primo a partire
while (1)
{
while(flag==0) sigsuspend(&newmask);
flag=0;
printf("%d,ho ricevuto il token\n",getpid());
sleep(1);
printf("%d,spedisco il token al processo %d\n",getpid(),root_pid);
kill(root_pid,SIGUSR1);
}
else 
    {/*parent*/
while(1)
{
while(flag==0) sigsuspend(&newmask);
flag=0;
printf("%d,ho ricevuto il token\n",getpid());
sleep(1);
printf("%d,spedisco il token al processo %d\n",getpid(),pid);
kill(pid,SIGUSR1);
}
waitpid(pid,NULL,0);
}
}
12 notes · View notes
guidabasec-blog · 14 years ago
Text
sync padre figlio
/* Il processo padre e il processo figlio si sincronizzano tramite le SIGNAL */
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <stdlib.h>
pid_t pidParent, pidChild1, pidChild2;
void sigHandler(int signo)
{
int status;
if(signo == SIGCHLD)
{
wait(&status);
printf("Il figlio è terminato con status %d.\n", status>>8);
}
return;
}
int main(int argc, char* argv[])
{
pid_t pid;
int i;
pidParent = getpid();
printf("Pid del genitore : %d\n", getpid());
/* SIGCHLD viene inviata al padre quando un figlio termina */
  /* Si può prelevare lo status del figlio terminante con una wait() all'interno del gestore dei segnali */
if(signal(SIGCHLD, sigHandler) == SIG_ERR) perror("signal():");
/* Primo figlio */
if((pid = fork()) == 0)
{
/* Il figlio si ferma con pause(), ossia si risveglierà quando gli arriverà un segnale */
printf("Creazione del 1° figlio con pid %d.\n", getpid());
pause();
exit(0);
}
else if(pid < 0) perror("fork():");
else pidChild1 = pid;
sleep(2);
printf("Il pid del 1° è %d\n", pidChild1);
/* Secondo figlio */
if((pid = fork()) == 0)
{
/* Il figlio anche qui si ferma con pause() in attesa di un segnale */
printf("Creazione del 2° figlio con pid %d.\n", getpid());
pause();
exit(0);
}
else if(pid < 0) perror("fork():");
else pidChild2 = pid;
sleep(2);
printf("Il pid del 2° è %d\n", pidChild2);
printf("Uccisione del primo figlio con pid %d.\n", pidChild1);
/* Il padre ammazza i figli con kill(pid, SIGKILL) */
if(kill(pidChild1, SIGKILL) == -1) perror("kill():");
sleep(2);
printf("Uccisione del secondo figlio con pid %d.\n", pidChild2);
if(kill(pidChild2, SIGKILL) == -1) perror("kill():");
sleep(2);
printf("E ora anche il padre termina.\n");
return 0;
}
21 notes · View notes
guidabasec-blog · 14 years ago
Text
stringhe
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h> 
//prendo i parametri e li metto in una stringa
int main(int argc, char *argv[]) 
int i;
char *comando; 
for(i=0; i<argc; i++) 
comando=argv[i]; 
printf("%s\n", comando);
}
}
// se voglio invece fare un array di stringhe 
/*
int main(int argc, char* argv[]) {
char** buffer;
int i,j;
buffer = (char**)malloc(sizeof(char*)*argc);
int k =0;
for (j=1; j<=argc; j++){
buffer[k]=(char*)malloc(sizeof(argv[j]));
buffer[k]=argv[j];
printf("%s\n", buffer[k]);
k++;
}
}
*/
0 notes
guidabasec-blog · 14 years ago
Text
stampa alla fine
/*
Esercizio1 (obbligatorio): (20 punti) Scrivere un programma in linguaggio C denominato “stampallafine” che tramite la
chiamata open_memstream (leggere il man!) salvi tutto cio' che riceve da standard input in una stringa. Quando lo
standard input termina, l'intera stringa deve essere copiata sullo standard output.
(Ricordate di definire la costante _GNU_SOURCE prima di includere stdio.h)
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main(int argc, char* argv[])
{
char *ptr;
char *v;
size_t size, sizeloc, nmemb;
FILE *in;
int ris;
/* Ptr è il puntatore all'area di memoria allocata dinamicamente per l'input */
/* In è il file descriptor dell'input */
if((in = open_memstream(&ptr, &sizeloc)) == NULL) perror("main:");
while(scanf("%m[a-z % ? ! _ - 0-9 ^]", &v)) /* soluzione alquanto pacchiana */
{
/* fprintf scrive sul file in ciò che è letto da input */
fprintf(in, "%s", v);
}
fclose(in);
fprintf(stdout, "%s\n", ptr);
free(ptr);
free(v);
return 0;
}
0 notes
guidabasec-blog · 14 years ago
Text
Sort dir al contrario
/* Esercizio1 (obbligatorio): (20 punti) Usando le chiamate opendir, readdir, closedir, qsort realizzare un programma in */
/* linguaggio C che metta in output la lista dei file della directory corrente in ordine alfabetico inverso. */
/* (l'output deve essere equivalente a quello del comando “ls . | sort -r”). */
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdlib.h>
static int compare(const void * a, const void * b)
{
return strcmp(* (char * const *) a, * (char * const *) b);
}
int main(int argc, char* argv[])
{
/* La struttura dirent vale per un singolo file e non per tutto il contenuto della cartella */
struct dirent *curDir;
struct dirent allFiles[1024];
char *stringhe[1024][255];
/* Il tipo DIR vale per una singola directory */
DIR *dd;
int ris, i, count;
count = 0;
/* Apre la directory corrente */
if((dd = opendir(".")) == NULL)
{
perror("main:");
exit(1);
}
/* La legge */
while(curDir = readdir(dd))
{
/* Memorizza tutti i file presenti */
if(curDir->d_type == DT_REG)
{
allFiles[count] = *curDir;
count++;
}
}
/* Stampa i file in ordine di lettura */
for(i=0; i<=count; i++)
printf("%s\n", allFiles[i].d_name);
/* Salva i nomi in una matrice di stringhe */
for(i=0; i<=count; i++)
stringhe[i][0] = allFiles[i].d_name;
/* Li ordina */
qsort(stringhe[1], count, sizeof(char *), compare);
/* E li ristampa */
for(i=0; i<=count; i++)
printf("%s\n", allFiles[i].d_name);
if((ris = closedir(dd)) == -1)
{
perror("main:");
exit(1);
}
return 0;
}
309 notes · View notes
guidabasec-blog · 14 years ago
Text
somma
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
/* Numero di giocatori nel sistema */
#define NPROCESSI 5
/* Scrive un messaggio di errore e poi termina */
void errquit(char* message)
{
  perror(message);
  exit(1);
}
int main(int argc, char* argv[])
{
  /* Process id ottenuto da fork */
  int pid;
  /* Indice del processo */
  int index = 1;
  /* Pipe utilizzato dal parent per leggere il risultato finale */
  int parentpipe[2];
  /* File descriptor per costruire pipe */
  int fd[2];
  /* File descriptor da utilizzare per leggere/scrivere */
  int fdin, fdout;
  /* Valore da leggere */
  int valore;
  /* Counter */
  int i;
  /* Creo il pipe affinche' il parent legga il risultato finale */
  if (pipe(parentpipe) < 0) {
    errquit("PIPE error");
  }
  /* Faccio il fork di NGIOCATORI figli */
  index = 1;
  for (i=2; i <= NPROCESSI; i ++) {
    if (pipe(fd) < 0) {
      errquit("PIPE error");
    }
    pid = fork();
    if (pid < 0) {
      errquit("FORK error");
    } else if (pid == 0) {
      /* Child (index = i)*/
      fdin = fd[0];
      index = i;
    } else {
      /* Parent (index = i-1) */
      fdout = fd[1];
      break;
    }
  }
  /* Scelgo cosa fare, a seconda che sia padre e/o figlio */
  if (index == 1) {
    /* Primo processo */
    fdin = parentpipe[0];
    valore = 1;
    printf("process[%d]: mandato %d\n", index, valore);
    if (write(fdout, &valore, sizeof(int))<0) { 
      errquit("WRITE error");
    }
    if (read(fdin, &valore, sizeof(int))<0) {
      errquit("READ error");
    }
    printf("process[%d]: ricevuto %d\n", index, valore);
  } else if (index == NPROCESSI) {
    /* Ultimo processo */
    fdout = parentpipe[1];
    if (read(fdin, &valore, sizeof(int))<0) {
      errquit("READ error");
    }
    printf("process[%d]: ricevuto %d\n", index, valore);
    valore = valore + index;
    printf("process[%d]: mandato %d\n", index, valore);
    if (write(fdout, &valore, sizeof(int))<0) { 
      errquit("WRITE error");
    }
  } else {
    /* Processi intermedi */
    if (read(fdin, &valore, sizeof(int))<0) {
      errquit("READ error");
    }
    printf("process[%d]: ricevuto %d\n", index, valore);
    valore = valore + index;
    printf("process[%d]: mandato %d\n", index, valore);
    if (write(fdout, &valore, sizeof(int))<0) { 
      errquit("WRITE error");
    }
  }
}
2 notes · View notes
guidabasec-blog · 14 years ago
Text
Socket server
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#define NAME "socket"
int main(int argc, char *argv[])
{
  int sock, msgsock, rval;
  struct sockaddr_un server;
  char buf[1024];
  sock = socket(AF_UNIX, SOCK_STREAM, 0);
  if (sock < 0) {
    perror("opening stream socket");
    exit(1);
  }
  server.sun_family = AF_UNIX;
  strcpy(server.sun_path, NAME);
  if (bind(sock, (struct sockaddr *) &server, sizeof(struct sockaddr_un))) {
    perror("binding stream socket");
    exit(1);
  }
  printf("Socket has name %s\n", server.sun_path);
  listen(sock, 5);
  for (;;) {
    msgsock = accept(sock, 0, 0);
    if (msgsock == -1)
      perror("accept");
    else do {
      bzero(buf, sizeof(buf));
      if ((rval = read(msgsock, buf, 1024)) < 0)
        perror("reading stream message");
      else if (rval == 0)
        printf("Ending connection\n");
      else
        printf("-->%s\n", buf);
      } while (rval > 0);
    close(msgsock);
  }
  close(sock);
  unlink(NAME);
}
15 notes · View notes
guidabasec-blog · 14 years ago
Text
socket client
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#define DATA "Laboratorio di S.O."
int main(int argc, char *argv[])
{
  int sock;
  struct sockaddr_un server;
  char buf[1024];
  if (argc < 2) {
    printf("usage:%s <pathname>", argv[0]);
    exit(1);
  }
  sock = socket(AF_UNIX, SOCK_STREAM, 0);
  if (sock < 0) {
    perror("opening stream socket");
    exit(1);
  }
  server.sun_family = AF_UNIX;
  strcpy(server.sun_path, argv[1]);
  if (connect(sock, (struct sockaddr *) &server, sizeof(struct sockaddr_un)) < 0) {
    close(sock);
    perror("connecting stream socket");
    exit(1);
  }
  if (write(sock, DATA, sizeof(DATA)) < 0)
     perror("writing on stream socket");
  }
  close(sock);
}
0 notes
guidabasec-blog · 14 years ago
Text
sigusr2
#include  <signal.h>
#include  <unistd.h>
static void sig_usr(int); /* one handler for both signals */
int
main(void)
{
  if (signal(SIGUSR1, sig_usr) == SIG_ERR)
    perror("can't catch SIGUSR1");
  if (signal(SIGUSR2, sig_usr) == SIG_ERR)
    perror("can't catch SIGUSR2");
  for ( ; ; )
    pause();
}
static void
sig_usr(int signo)    /* argument is signal number */
{
  if (signo == SIGUSR1)
    printf("received SIGUSR1\n");
  else if (signo == SIGUSR2)
    printf("received SIGUSR2\n");
  else {
    printf("received signal %d\n", signo);
    abort();
    exit(1);
  }
  return;
}
0 notes
guidabasec-blog · 14 years ago
Text
Sigusr1
 #include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
int c,i;
void sig_handler () {
i = 0;
printf("entro nella signal\n");
printf("%d\n", c);
}
int main() {
pid_t pid, pidp;
pid = fork();
if (pid==0) {
sleep(5);
printf("sono il figlio\n");
pidp = getppid();
i=0;
kill(pidp, SIGUSR1);
printf("ho mandato la kill\n");
} else {
i = 1;
printf("sono il padre\n");
while (i!=0) {
c++;
printf("ciclo\n");
sleep(1);
signal(SIGUSR1, sig_handler);
}
}
}
0 notes
guidabasec-blog · 14 years ago
Text
Signal
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
void my_sigaction(int sig, siginfo_t *siginfo, void *data) {
pid_t pid_sender = siginfo->si_pid;
if (kill(pid_sender, sig)) perror("Errore nella kill");
  }
int main() {
// i segnali che vuoi intecettare
int signals[] = {SIGTERM, SIGINT, SIGCHLD};
int num_sig = 3;
int i;
// la struttura da passare a sigaction
struct sigaction action;
        // va impostato quando usi sa_sigaction invece di sa_handler
action.sa_flags = SA_SIGINFO;
// imposti la funzione da eseguire quando viene intercettato lo specifico segnale
action.sa_sigaction = my_sigaction;
        // chiama sigaction su ogni segnale specificato da te in signals[]
for (i = 0; i < num_sig; i++) {
if (sigaction(signals[i], &action, NULL)) perror("Errore nella sigaction");
}
}
18 notes · View notes
guidabasec-blog · 14 years ago
Text
ora esatta
/********************************************************************************/
/*Usare la system call setitimer per creare un programma che stampi l'ora esatta*/
/*a intervalli regolari.La durata dell'intervallo e' specificata in millisecondi*/
/*come parametro. */
/********************************************************************************/
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
sig_t stampaData()
{
execlp("date","date",0);
}
int main(int argc, char* argv[]){
int ris;
struct itimerval time;
pid_t cpid;
sig_t hand;
/*imposto il periodo(it_interval)ad argv[1].*/
/*value e' il contatore che decrementa sempre */
/*quando arriva a 0 manda un segnale e lo risetta*/
/*al valore di it_interval*/
time.it_interval.tv_sec=0;
time.it_interval.tv_usec=atoi(argv[1])*1000;
time.it_value.tv_sec=0;
time.it_value.tv_usec=atoi(argv[1])*1000;
/*specifico il gestore che verra' usato dopo il segnale*/
hand = signal(SIGALRM,(sig_t)stampaData);
while(1)
{
cpid=vfork();
if(cpid==0)
{
/*con setitimer apetto un periodo e mando un segnale*/
ris=setitimer(ITIMER_REAL,&time,0);
/*mi addormento fino a quando arriva il segnale*/
pause();
/*gestisco il segnale altrimenti terinerebbe il processo*/
signal(SIGALRM,hand);
}
}
}
16 notes · View notes
guidabasec-blog · 14 years ago
Text
Select demo
/*
** select.c -- a select() demo
*/
#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#define STDIN 0  // file descriptor for standard input
int main(void)
{
struct timeval tv;
fd_set readfds;
tv.tv_sec = 2;
tv.tv_usec = 500000;
FD_ZERO(&readfds);
FD_SET(STDIN, &readfds);
// don't care about writefds and exceptfds:
select(STDIN+1, &readfds, NULL, NULL, &tv);
if (FD_ISSET(STDIN, &readfds))
printf("A key was pressed!\n");
else
printf("Timed out.\n");
return 0;
}
218 notes · View notes
guidabasec-blog · 14 years ago
Text
Select Ora esatta
// Scrivere un programma che copi lo standard input nello standard output, aggiungendo in quest'ultimo 
// la riga con l'ora esatta ogni 5 secondi. Il programma deve essere composto da un solo processo 
// (non fare fork).
#include <sys/time.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/select.h>
#include <stdio.h>
#include <stdlib.h>
/* stampa l'ora corrente */
void oraEsatta()
{
           char outstr[200];
           time_t t=time(NULL);
  strftime(outstr, sizeof(outstr),"%T", localtime(&t));
           printf("%s\n", outstr);
int main(){
struct timeval time;
fd_set readset,writeset;
time.tv_sec=5;
time.tv_usec=0;
char buff;
int nready;
while(1)
{
FD_ZERO(&readset);
FD_SET(STDIN_FILENO,&readset);
  nready = select(STDIN_FILENO+1,&readset,NULL,NULL,&time);
  if(nready == 0) // timeout
{
time.tv_sec=5;
oraEsatta();
} else // descrittore pronto
{
read(STDIN_FILENO,&buff,1);
write(STDOUT_FILENO,&buff,1);
}
}
}
226 notes · View notes