Isn't it cleaner to use systemd / services in order to do so ?
It is explained here how to cycle between 2 services:
For kodi.service (configured as a user service not system wide service contrary to the above link) :[unit] ... Conflicts = emulstation.service ... [service] ... ExecStopPost = /usr/bin/systemctl --user start emulstation.service ...
And for emulstation.service[unit] ... Conflicts = kodi.service ... [service] ... ExecStopPost = /usr/bin/systemctl --user start kodi.service ...
Emulstation and kodi should not be services enabled/start by default at boot but rather
autostart.sh start the first service by something like:
if kodi is configured to be the first one.
To go further we can also think about replacing the autostart script by a retropie service which is enabled at boot time. At start, it launches the first configured service. At stop it ensures that emulstation and kodi are stoped.
If the service is run as pi user (which is more secure), the pi user must be lingered to enable autostart of the service at boot even if the user is not logged in.loginctl enable-linger pi systemctl --user enable retropie
Advantages:All the services could be controlled, inspected, logged through the systemd tools Not need for automatic login It could be easily extended to any number of services not just 2.