9.11 El código de dc.c

/******************************************************************************  
 * dc.c -- Un generador de señal constante (Direct Current).  
 *  
 * gse. 2005.  
 *****************************************************************************/  
 
/******************************************************************************  
 *  
 * Ficheros cabecera.  
 *  
 *****************************************************************************/  
 
/* Entrada y salida de streams buffereados. */  
#include <stdio.h>  
 
/* Biblioteca de funciones estándar (exit(), EXIT_SUCCESS,  
   EXIT_FAILURE, ...) */  
#include <stdlib.h>  
 
/* Manipulación de cadenas y movimiento de memoria (memset(), ...). */  
#include <string.h>  
 
/* Biblioteca estándar de funciones relacionadas con el sistema  
   operativo Unix (read(), write(), getopt(), ...). */  
#include <unistd.h>  
 
/* Signals (interrupciones) (signal(), SIGINT). */  
#include <signal.h>  
 
/******************************************************************************  
 *  
 * Definiciones.  
 *  
 *****************************************************************************/  
 
/* Tamaño del buffer de datos. */  
#define BUFFER_SIZE 512  
 
/* Valor por defecto de la señal. */  
#define DC_VAL 1000  
 
/******************************************************************************  
 *  
 * Variable globales.  
 *  
 *****************************************************************************/  
 
/******************************************************************************  
 *  
 * Funciones.  
 *  
 *****************************************************************************/  
 
/* Cuerpo principal del programa. */  
int main(int argc, char *argv[]) {  
  work(argc, argv);  
  return EXIT_SUCCESS;  
}  
 
work(int argc, char *argv[]) {  
 
  /* Si pulsamos CRTL+C, el programa acaba ejecutando la función  
     end(). */  
  void end() {  
    fprintf(stderr,"%s: CTRL+C detected. Exiting ... ",argv[0]);  
    fprintf(stderr,"done\n");  
    exit(EXIT_SUCCESS);  
  }  
  signal(SIGINT, end);  //activando la senal SIGINT  
 
  /* Valor de la señal DC. */  
  int dc_val = DC_VAL;  
 
int c;  
  while ((c = getopt (argc, argv, "v:")) != -1) {  
    switch (c) {  
    case ’v’:  
      dc_val = atoi(optarg);  
      break;  
    case ’?’:  
      if (isprint (optopt))  
        fprintf (stderr, "Unknown option ‘-%c’.\n", optopt);  
      else  
        fprintf (stderr,  
                 "Unknown option character ‘\\x%x’.\n",  
                 optopt);  
      return 1;  
    default:  
      abort ();  
    }  
  }  
 
  fprintf(stderr,"%s: DC value = \"%d\"\n",  
          argv[0],dc_val);  
 
  for(;;) {  
    short buffer[BUFFER_SIZE/sizeof(short)];  
    int i;  
    for(i=0; i<BUFFER_SIZE/sizeof(short); i++) {  
      buffer[i] = dc_val;  
    }  
    write(1, (void *)buffer, BUFFER_SIZE);  
  }  
 
}