How to exit from emulators using gamepad short cuts

I am running a small linux box connected to my TV for playing retro games in emulators. I had serious problems getting retroarch (libretro) on gentoo up for running my N64 games because the required version of the emulator (mupen64plus) was way too buggy. However, the latest unstable version of standalone mupen (using an overlay) was able to run my Mario Kart 64 without texture glitches :-D

You can easily fire up games with a gamepad using emulationstation. And you can even shut down or run custom scripts with this frontend. But one thing was missing: Quitting the emulator without a keyboard or an IR-remote. As I use all the buttons of my gamepads for the games, defining one button to exit in the emulators key mapping was no option. I needed a way use a button combination for it.

I figured out how to put together a chain of three components to exit a running emulator without a keyboard.

First the ugly part: I use a „killall -9 emu“ to „end“ the emulator. To execute this command I use xbindkeys. It is a small daemon that listens for pressed key sequences. My config looks like this:
"killall -9 mupen64plus"
control + q

It listens for the control and q keys pressed and fires the killall. That’s it.

Having xbindkeys running in background I am able to stop the emulator with the keyboard shortcut. But unfortunately xbindkeys is not able to listen for gamepad buttons.

For the next step I need the gamepads button numbers for the combo. I used the GUI of mupen64 where you set up the key mapping. The GUI lists the pressed buttons numbers. In my case it is number 8 and 9.
Now I use the Xorg conf to map these buttons to the keyboard signals for „control“ and „q“.

Edit Xorg’s gamepad config /etc/X11/xorg.conf.d/50-joystick-all.conf:
Section "InputClass"
Identifier "joystick-all"
Driver "joystick"
MatchIsJoystick "on"
MatchDevicePath "/dev/input/event*"
Option "StartMouseEnabled" "false"
Option "MapButton8" "key=24"
Option "MapButton9" "key=37"

To get the codes 24 and 37 for the control and q-keys I used the command
# xbindkeys -k
It opens a small window and shows the key codes when a button is pressed.

When I press the buttons 8 and 9 on my gamepad now the X server tells the X environment that keys control and q are pressed. This gets caught by xbindkeys and it runs the killall -> Emu gets closed.

Have fun :-)