Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect when the user has pressed the power off button?

I have an arcade cocktail cabinet (no keyboard, just a joystick and buttons) running Ubuntu 12.4.1, when the power button is pressed a popup appears and the system shuts down fine, but when my full-screen game launcher menu application is running then pressing the button has no effect. I would like to trap the event when the button is pressed so my app can trigger the system shutdown. My menu app is written in c++ and is using SDL. Any ideas on how I can trap the power off button press event?

Thanks to those that responded, here is the actual code I used to get it to work:

Class members:

int m_acpidsock;
sockaddr_un m_acpidsockaddr;

Setup code:

/* Connect to acpid socket */
m_acpidsock = socket(AF_UNIX, SOCK_STREAM, 0);
if(m_acpidsock>=0)
{
    m_acpidsockaddr.sun_family = AF_UNIX;
    strcpy(m_acpidsockaddr.sun_path,"/var/run/acpid.socket");
    if(connect(m_acpidsock, (struct sockaddr *)&m_acpidsockaddr, 108)<0)
    {
        /* can't connect */
        close(m_acpidsock);
        m_acpidsock=-1;
    }
}

Update code:

/* check for any power events */
if(m_acpidsock)
{
    char buf[1024];
    int s=recv(m_acpidsock, buf, sizeof(buf), MSG_DONTWAIT);

    if(s>0)
    {
        buf[s]=0;
        printf("ACPID:%s\n\n",buf);
        if(!strncmp(buf,"button/power",12))
        {
            setShutdown();
            system("shutdown -P now");
        }
    }
}

Close socket code:

if(m_acpidsock>=0)
{
    close(m_acpidsock);
    m_acpidsock=-1;
}

Lastly, I needed to allow non-root users to shutdown and that worked using this line:

sudo chmod u+s /sbin/shutdown
like image 871
KPexEA Avatar asked Dec 24 '12 21:12

KPexEA


2 Answers

You could just start a thread to read from /proc/events/acpi, and decode the messages there.

But how about using acpid to do that? You'd listen to the /var/run/acpid.socket, and when a message you care about comes in, do what you have do to.

See: http://www.linuxmanpages.com/man8/acpid.8.php

I hope this is useful.

like image 132
Mats Petersson Avatar answered Sep 20 '22 17:09

Mats Petersson


Have a look at acpid, I think you could change one of the scripts in /etc/acpi/ specifically /etc/acpi/powerbtn.sh to add custom commands. You could also try reading /proc/acpi/event yourself.

like image 23
iabdalkader Avatar answered Sep 21 '22 17:09

iabdalkader