Loginctl Hooks Not Working: Expected Sessions in Suspend Mode

Abstract: Resolve loginctl hooks failing to lock sessions during suspend on OpenRC by configuring a custom /etc/sleep.d script.

Created: 2026-08-31 by

Loginctl hooks fail to lock sessions during suspend on OpenRC because the init system does not execute standard systemd sleep scripts or invoke loginctl automatically. To resolve this, you must configure a custom OpenRC hook in /etc/sleep.d that manually calls loginctl lock-session for active users before the system enters the suspended state.

Understanding the Mechanism Mismatch

The core issue arises from a fundamental architectural difference between systemd and OpenRC. On systems managed by systemd, the daemon handles power management events through specific hooks located in /lib/systemd/system-sleep/ or via D-Bus signals. When the system prepares to suspend, systemd triggers these scripts, which often include logic to lock user sessions using loginctl lock-session. This ensures that sensitive data is protected before the RAM is retained in a low-power state. OpenRC, however, operates independently of systemd. It does not natively understand systemd-specific paths or D-Bus session locking mechanisms in the same way. While OpenRC has its own sleep handling infrastructure, it does not automatically iterate through active login sessions to lock them. If you rely on the default behavior expected from a systemd environment, the sessions will remain unlocked when the machine suspends, leaving your data vulnerable if the device is stolen or accessed while powered off. This mismatch is particularly noticeable when using desktop environments that expect seamless integration with the underlying init system's power management. Users switching from Ubuntu (which uses systemd) to Debian with OpenRC, or those configuring minimal Linux installations, frequently encounter this gap. The absence of automatic locking is not a bug in OpenRC but a result of its modular design, where such tasks must be explicitly configured by the administrator.

Configuring the OpenRC Sleep Hook

To fix this, you need to create a script that OpenRC will execute during the sleep transition. OpenRC uses the directory /etc/sleep.d for custom scripts that run at various stages of the sleep/wake cycle. These scripts receive arguments indicating the action (e.g., prepare, post, thaw, resume). Create a new executable file in /etc/sleep.d. A common convention is to name it with a prefix number to control execution order, such as 99-lock-sessions. Ensure the file has execute permissions.
# /etc/sleep.d/99-lock-sessions
#!/bin/sh

case "$1" in
    prepare)
        # Lock all active sessions before suspending
        for session in $(loginctl list-sessions --no-legend | awk '{print $1}'); do
            loginctl lock-session "$session"
        done
        ;;
esac
The script checks if the argument passed by OpenRC is prepare. This phase occurs just before the system actually enters the low-power state, providing the perfect window to secure active sessions. The command loginctl list-sessions retrieves all active session IDs. We pipe this output to awk to extract only the first column, which contains the session ID. Finally, we loop through each ID and call loginctl lock-session to enforce the lock. It is crucial to use prepare rather than suspend directly if available, as some hardware drivers may initialize sleep modes before scripts run. However, on many OpenRC setups, prepare is the most reliable trigger for pre-suspend actions. If your system uses a different trigger mechanism, adjust the case statement accordingly.

Verifying Session State

Before testing, verify that you have active sessions. You can check this by running loginctl list-sessions in your terminal. If you are logged in via a graphical interface, you should see at least one session. After applying the script, suspend your system using the standard method provided by your desktop environment or by running systemctl suspend (if systemd-shim is installed) or openrc-sleep commands depending on your setup. Upon waking, you should be prompted for a password before accessing the desktop or terminal, confirming that the hook worked correctly. For more details on how OpenRC manages service shutdowns and ordering, which can sometimes interfere with sleep hooks if misconfigured, see our guide on Preserve Order of Closing Services While Shutting Down Linux.

Alternative Approaches and Desktop Integration

If creating a global hook feels too intrusive, some desktop environments offer their own session locking mechanisms. For instance, KDE Plasma and GNOME have settings within their power management panels that can trigger screen locks before sleep. However, these are often limited to the graphical session and may not lock SSH sessions or TTYs. The OpenRC hook approach is superior because it acts at the system level, ensuring every session managed by logind is secured regardless of how the user interacts with the machine. Another consideration is the interaction with hibernation. If you use hibernation alongside suspend, ensure your hook also handles the hibernate action in the case statement. Hibernation writes memory to disk and powers off completely, making security even more critical. For users dealing with broader sleep issues, such as systems failing to wake up properly, check your kernel parameters and ACPI tables. Issues with resume states can sometimes mask problems with pre-suspend actions. Our article on Unable to awaken Debian 12 Linux under sleep/suspend provides troubleshooting steps for wake failures that might co-occur with locking issues.

Common Pitfalls

One common mistake is forgetting to make the script executable. Without the execute bit, OpenRC will silently ignore the file. Use chmod +x /etc/sleep.d/99-lock-sessions to fix this. Another pitfall is assuming that loginctl is always available in the path. In minimal OpenRC installations, you might need to install the util-linux package if it isn't already present, as loginctl is part of this suite. Additionally, ensure that your user has permission to lock other sessions. Usually, root can lock any session, so running the script as root (which OpenRC does for sleep hooks) avoids permission errors. Finally, test the script manually by calling it with sudo /etc/sleep.d/99-lock-sessions prepare. This simulates the environment without actually suspending the machine, allowing you to check for syntax errors or missing commands.

Frequently Asked Questions

Why doesn't OpenRC lock sessions automatically?

OpenRC is designed to be modular and does not include default behaviors for every possible desktop feature like session locking. Unlike systemd, which integrates deeply with logind, OpenRC requires administrators to explicitly define such interactions through custom scripts in /etc/sleep.d.

Can I use systemd-sleep scripts with OpenRC?

No, OpenRC cannot execute systemd-specific scripts located in /lib/systemd/system-sleep/. These scripts are tied to the systemd daemon lifecycle. You must write native shell scripts compatible with OpenRC's sleep interface instead.

What happens if the lock script fails?

If the script encounters an error, the system will still proceed to suspend unless the script exits with a non-zero status that halts the process. Typically, minor errors in the locking loop won't stop suspension, but the sessions will remain unlocked. Check logs in /var/log/messages or /var/log/syslog for details on why a script might fail.

Does this work for remote SSH sessions?

Yes, because loginctl manages all sessions registered with logind, including those created by SSH daemons. The script iterates over all active session IDs, ensuring that remote terminals are also locked before the system sleeps.

How do I disable the lock for specific users?

You would need to modify the script to filter out specific UIDs or usernames. Iterate through the sessions, check the owner of each session using loginctl show-session, and skip the lock command if the user matches your exclusion list.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More