#include #include #include #include #include #include #include #define BUTTON_DEV "/dev/ppb" #define USLEEP_TIME 50000 /* sleep 0.05 s*/ #define NO_OF_BUTTONS 4 #define PRESSED 0 #define RELEASED 1 static int daemon_mode = 0; static char * actions[2 * NO_OF_BUTTONS] = { NULL, NULL, "halt", NULL, NULL, NULL, NULL, NULL, }; void usage () { fprintf(stderr, "Usage: button_exec [-d] \n"); } void action (int act, int button) { char * command; command = actions[act + 2*button]; if (command != NULL) { if (system(command) < 0) { perror("action"); } } } void check (unsigned char old_data, unsigned char new_data) { int i, button; unsigned char changed; changed = old_data ^ new_data; for (i = 0; i < NO_OF_BUTTONS; i++) { button = 1 << i; if (changed & button) { if (new_data & button) { action(PRESSED, i); } else { action(RELEASED, i); } } } } int parse_commandline (int argc, char ** argv) { int i; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "-d") == 0) { daemon_mode = 1; } else { return 2; } } return 0; } int main (int argc, char ** argv) { int fd, r, daemon_mode = 0; unsigned char old_data, data; if (parse_commandline(argc, argv) != 0) { usage(); return 2; } fd = open(BUTTON_DEV, O_RDONLY); if (fd < 0) { perror("Error opening key device"); return 1; } if (daemon_mode) { if (daemon(0, 1) == -1) { perror("Error detaching"); return 1; } } while (1) { r = read(fd, &old_data, 1); if (r < 0) { perror("Read error"); return 1; } do { usleep(USLEEP_TIME); r = read(fd, &data, 1); if (r < 0) { perror("Read error"); return 1; } } while (data == old_data); check(old_data, data); } }