8

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
KPexEA
  • 16,560
  • 16
  • 61
  • 78

3 Answers3

5

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.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
2

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.

iabdalkader
  • 17,009
  • 4
  • 47
  • 74
2

Things like pressing the power button trigger ACPI events which acpid fires off a script in response to as configured in /etc/acpi/events. In this case you want /etc/acpi/powerbtn, which looks something like this:

event=button[ /]power
action=/etc/acpi/powerbtn.sh

You can either customize /etc/acpi/powerbtn.sh, or point it at another script of your choosing.

Vinay Pai
  • 7,432
  • 1
  • 17
  • 28