Tiny Core Linux
Tiny Core Base => Raspberry Pi => Topic started by: Rabie on October 15, 2025, 05:17:13 AM
-
Hi,
How can I get the Pi 5 to run the command "sudo poweroff" when I press the power button? Thanks in advance
-
okay I made a C Skript and compiled it, then i put it in bootlocal.sh and it worked.
The Topic is now solved.
Sorry for not trying alone before.
cat /opt/Scripts/psw_shutdown.c
#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;
}
}
close(fd);
return 0;
}
-
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.
-
hi Rich,
i see this
Mem: 823732K used, 7315548K free, 100576K shrd, 316K buff, 499368K cached
CPU: 0.8% usr 0.3% sys 0.0% nic 98.7% idle 0.0% io 0.0% irq 0.0% sirq
Load average: 0.05 0.12 0.09 2/162 4914
PID PPID USER STAT VSZ %VSZ CPU %CPU COMMAND
3249 1 root S 1748 0.0 0 0.0 /opt/Scripts/psw_shutdown
I am not realy a pro so I don't really understand, if thats a lot.
but I think it looks fine.
what do u think ?
-
Hi Rabie
I must admit, I am surprised. That does look fine.
Usually a loop like that will keep a CPU very busy.