Hi Rabie
Looks good, but I suspect it may be consuming a lot of
CPU cycles. If you run top , does it show psw_shutdown
consuming a large percentage of CPU clock cycles?
I would have done something to slow the while() loop
down, for instance:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/input.h>
#define DEVICE "/dev/input/event0"
int main() {
struct input_event ev;
int fd = open(DEVICE, O_RDONLY);
if (fd == -1) {
perror("Failed to open input device");
return 1;
}
printf("Listening for PSW button on %s...\n", DEVICE);
while (1) {
if (read(fd, &ev, sizeof(struct input_event)) == -1) {
perror("Failed to read input event");
close(fd);
return 1;
}
if (ev.type == EV_KEY && ev.code == KEY_POWER && ev.value == 1) {
printf("Power button pressed! Shutting down...\n");
system("sudo poweroff");
break;
}
usleep(250000); // Limit polling rate to 4 times per second.
}
close(fd);
return 0;
}
That would be the simplest way of taming that loop.
A more advanced way would be to monitor the fd
using a select() instruction, but the usleep() is
quite sufficient for this application.