Skip to content

Instantly share code, notes, and snippets.

@enko
Created October 30, 2012 22:33
Show Gist options
  • Select an option

  • Save enko/3983546 to your computer and use it in GitHub Desktop.

Select an option

Save enko/3983546 to your computer and use it in GitHub Desktop.
#include <fcntl.h>
#include <getopt.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <linux/kd.h>
#ifndef CLOCK_TICK_RATE
#define CLOCK_TICK_RATE 1193180
#endif
/* Meaningful Defaults */
#define DEFAULT_FREQ 440.0 /* Middle A */
#define DEFAULT_LENGTH 200 /* milliseconds */
#define DEFAULT_REPS 1
#define DEFAULT_DELAY 100 /* milliseconds */
#define DEFAULT_END_DELAY NO_END_DELAY
#define DEFAULT_STDIN_BEEP NO_STDIN_BEEP
/* Other Constants */
#define NO_END_DELAY 0
#define YES_END_DELAY 1
#define NO_STDIN_BEEP 0
#define LINE_STDIN_BEEP 1
#define CHAR_STDIN_BEEP 2
typedef struct beep_parms_t {
float freq; /* tone frequency (Hz) */
int length; /* tone length (ms) */
int reps; /* # of repetitions */
int delay; /* delay between reps (ms) */
int end_delay; /* do we delay after last rep? */
int stdin_beep; /* are we using stdin triggers? We have three options:
- just beep and terminate (default)
- beep after a line of input
- beep after a character of input
In the latter two cases, pass the text back out again,
so that beep can be tucked appropriately into a text-
processing pipe.
*/
struct beep_parms_t *next; /* in case -n/--new is used. */
} beep_parms_t;
int console_fd = -1;
void play_beep(beep_parms_t parms) {
int i; /* loop counter */
/* try to snag the console */
if((console_fd = open("/dev/console", O_WRONLY)) == -1) {
fprintf(stderr, "Could not open /dev/console for writing.\n");
printf("\a"); /* Output the only beep we can, in an effort to fall back on usefulness */
perror("open");
exit(1);
}
/* Beep */
for (i = 0; i < parms.reps; i++) { /* start beep */
if(ioctl(console_fd, KIOCSOUND, (int)(CLOCK_TICK_RATE/parms.freq)) < 0) {
printf("\a"); /* Output the only beep we can, in an effort to fall back on usefulness */
perror("ioctl");
}
/* Look ma, I'm not ansi C compatible! */
usleep(1000*parms.length); /* wait... */
ioctl(console_fd, KIOCSOUND, 0); /* stop beep */
if(parms.end_delay || (i+1 < parms.reps))
usleep(1000*parms.delay); /* wait... */
} /* repeat. */
close(console_fd);
}
#include <stdio.h>
#include "beep.h"
int main() {
beep_parms_t *parms = (beep_parms_t *)malloc(sizeof(beep_parms_t));
parms->freq = DEFAULT_FREQ;
parms->length = DEFAULT_LENGTH;
parms->reps = DEFAULT_REPS;
parms->delay = DEFAULT_DELAY;
parms->end_delay = DEFAULT_END_DELAY;
parms->stdin_beep = DEFAULT_STDIN_BEEP;
parms->next = NULL;
printf("Going to beep!\n");
play_beep(*parms);
free(parms);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment