Search code examples
linux-mint

Run scripts on start or end of xsession


I am trying to find a way to run a script on sleep before an x session ends, because the script requires an active x session to execute properly. Storing the script in /etc/pm/sleep.d did not work (and returned errors related to a non-existent x session). Any ideas where to put the script?

Update in response to comments

king@death-star /etc/acpi $ cat 01_revert_kb_on_sleep 
#!/bin/bash
touch ~/Desktop/touchfile_my_script_acpi
case "$1" in
hibernate|suspend)
sh -c "/home/king/Desktop/Scripts/rotate_desktop normal; /home/king/Desktop/Scripts/misc/my_keyboard on" 2> ~/Desktop/revert_kb_error_log.txt ;;
#thaw|resume)

king@death-star /etc/acpi $ ls
total 1MB
drwxr-xr-x   3 root root 1MB Jun 11 23:36 .
drwxr-xr-x 163 root root 1MB Jun 11 23:41 ..
-rwxr-xr-x   1 root root 1MB Jun 11 23:36 01_revert_kb_on_sleep

king@death-star /etc/acpi $ ps -ef| grep acpid
root      1070     1  0 23:41 ?        00:00:00 acpid -c /etc/acpi/events -s /var/run/acpid.socket
king      3499  2574  0 23:52 pts/2    00:00:00 grep --colour=auto acpid

Solution

  • Step 1.

    a. Enable and start the acpi service.

    b. Run the acpi_listen command and try putting the computer to sleep via various methods (pushing the power button, closing the lid, etc.)

    c. Find out what events are triggered, when you do the above. In my case they were: button/lid LID close and button/sleep SBTN 00000080 00000000

    Step 2.

    a. Create the file /etc/acpi/events/my_events with the following:

    event=(button/sleep SBTN|button/lid LID close)
    action=/etc/acpi/my_script.sh
    

    Substitute the events in the event= line with your events.

    b. Create the file /etc/acpi/my_script.sh with the following:

    #!/bin/sh
    /home/king/Desktop/Scripts/rotate_desktop normal
    /home/king/Desktop/Scripts/misc/my_keyboard on
    

    NB. You might need to add export DISPLAY=:0 before the scripts to get access to your X session.

    NB2: Your scripts will run with root user credentials. To run with your user credentials, you might want to do:

    sudo -u king /home/king/Desktop/Scripts/rotate_desktop normal
    sudo -u king /home/king/Desktop/Scripts/misc/my_keyboard on
    

    c. Make the file /etc/acpi/my_script.sh executable:

    chmod +x /etc/acpi/my_script.sh
    

    d. Restart the acpi service.

    Step 3. Share and enjoy.