使用systemctl --user可管理用户级后台服务,无需root权限。将.service文件放在~/.config/systemd/user/目录下,通过daemon-reload加载,再用start、enable等命令控制服务;配合loginctl enable-linger可使服务在用户登出后仍运行,适合个人后台任务。

在Linux里,管理用户自己的后台服务,
systemctl --user
要使用
systemctl --user
首先,你的服务单元文件(通常是
.service
~/.config/systemd/user/
比如,你想让一个名为
my-script.py
~/.config/systemd/user/my-app.service
[Unit] Description=我的自定义Python应用 After=network.target [Service] ExecStart=/usr/bin/python3 /home/youruser/scripts/my-script.py WorkingDirectory=/home/youruser/scripts/ Restart=on-failure StandardOutput=journal StandardError=journal [Install] WantedBy=default.target
注意把
youruser
文件创建好后,你需要告诉 systemd 你的用户配置变了:
systemctl --user daemon-reload
然后,你就可以像管理系统服务一样来操作它了: 启动服务:
systemctl --user start my-app.service
systemctl --user status my-app.service
systemctl --user enable my-app.service
systemctl --user disable my-app.service
systemctl --user stop my-app.service
查看所有用户服务:
systemctl --user list-units --type=service
这个问题问得好,很多人一开始都会有这个疑问。系统服务(由
systemctl
--user
但作为普通用户,我可能想跑个自己的私人工具,比如一个定时同步文件的脚本,一个个人用的本地开发服务器,或者某个GUI应用的后台守护进程。这些东西,我并不希望它需要root权限,也不希望它干扰到系统层面。更重要的是,它们往往只对我这个用户有用。
这时,
systemctl --user
.bashrc
cron
编写用户服务单元文件,其实和编写系统服务单元文件大同小异,只是关注点略有不同。核心还是围绕
[Unit]
[Service]
[Install]
在
[Unit]
Description
After
Wants
After=network.target
[Service]
ExecStart
WorkingDirectory
Restart=on-failure
StandardOutput=journal
StandardError=journal
journalctl
[Install]
enable
WantedBy=default.target
default.target
default.target
调试方面,最直接的办法就是查看服务状态和日志。
systemctl --user status your-service-name.service
journalctl --user -u your-service-name.service
我经常遇到的坑,除了路径问题,就是权限。比如你的脚本没有执行权限,或者它需要访问某个文件但当前用户没有权限。还有环境变量,有时候脚本依赖的环境变量在服务启动时并不存在,这时候你可能需要在
[Service]
Environment=
这是一个关键点,也是
systemctl --user
systemctl
但是,如果你确实有一些服务,希望它们在你登出后还能继续在后台运行,比如一个私人的数据同步守护进程,或者一个本地的Web服务,这时候就需要用到
loginctl enable-linger <username>
linger
systemctl --user enable
要启用
linger
sudo loginctl enable-linger yourusername
sudo loginctl disable-linger yourusername
linger
loginctl show-user yourusername
启用
linger
linger
以上就是如何在Linux中管理用户服务 Linux systemctl --user模式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号