#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <linux/kd.h>
#include <time.h>

/*
#include <ncurses.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <unistd.h>
#include <math.h>
*/

/* sudo visudo
 * add: user   ALL=NOPASSWD: /dev/console, /usr/sbin/beep */
/* sudo beep 1200 200 */

void beep(int tone, float milsec);

int main(int argc, char** argv){
    if( argc!=3 ) {
        printf("%s freq(Hz) duration(ms)\n",argv[0]);
        exit(-1);
    }
    beep( atoi(argv[1]), atof(argv[2]) );
    return 0;
}

void beep(int frequency, float milsec) {
    int fd;
    struct timespec time;

    fd = open("/dev/console", O_SYNC);
    //fd = open("/dev/tty0", O_SYNC);
    if( fd==-1 ) {
        printf("Error: can't open /dev/console\n");
        exit(-2);
    }

    time.tv_sec = ((int)milsec)/1e3;
    time.tv_nsec = (long)((milsec-time.tv_sec*1e3)*1e6);

    ioctl(fd, KIOCSOUND, (int)(1190000/frequency));
    nanosleep(&time, &time);

    /* stop tone */
    ioctl(fd, KIOCSOUND, 0);
    close(fd);
}

