使用systemctl --user可管理用户级服务,无需root权限,服务随用户登录启动、退出停止,适用于个人后台任务、开发环境及自动化脚本,配置文件位于~/.config/systemd/user/,通过enable实现开机自启,与系统服务隔离,安全且灵活。

在Linux中,如果你想管理那些只为你自己运行,不依赖于root权限,并且在你登录时启动、退出时停止的服务,那么
systemctl --user
要管理Linux中的用户服务,核心就是使用
systemctl --user
systemctl
你可以通过以下基本命令来操作用户服务:
systemctl --user start <服务名>.service
systemctl --user stop <服务名>.service
systemctl --user restart <服务名>.service
systemctl --user status <服务名>.service
systemctl --user enable <服务名>.service
systemctl --user disable <服务名>.service
systemctl --user list-units --type=service
systemctl --user daemon-reload
服务文件通常存放在
~/.config/systemd/user/
my-app.service
这确实是一个很多人初次接触时会感到困惑的地方,包括我自己。最核心的区别在于它们的作用域和权限。普通的
systemctl
--user
nginx
mysql
而
systemctl --user
logind.conf
KillUserProcesses=no
linger
/etc/systemd/system/
/usr/lib/systemd/system/
~/.config/systemd/user/
简单来说,如果你想让一个程序在后台为你个人工作,不需要root权限,并且与你的登录状态关联,那么
systemctl --user
创建用户服务比你想象的要简单,我个人觉得它比写
init.d
rc.local
.service
假设你想创建一个服务来运行一个Python脚本,比如一个定时抓取天气信息的脚本
~/scripts/weather_fetcher.py
第一步:创建服务文件
在
~/.config/systemd/user/
weather-fetcher.service
[Unit] Description=My personal weather data fetcher After=network-online.target [Service] ExecStart=/usr/bin/python3 /home/yourusername/scripts/weather_fetcher.py Restart=on-failure RestartSec=5s StandardOutput=journal StandardError=journal [Install] WantedBy=default.target
文件内容解释:
[Unit]
Description
After=network-online.target
[Service]
ExecStart
yourusername
Restart=on-failure
on-failure
RestartSec=5s
StandardOutput=journal
StandardError=journal
journalctl --user -u weather-fetcher.service
[Install]
WantedBy=default.target
default.target
第二步:重新加载systemd配置
在你修改或添加了服务文件后,需要让systemd重新读取配置:
systemctl --user daemon-reload
第三步:启动和启用服务
现在你可以启动你的服务了:
systemctl --user start weather-fetcher.service
并检查它的状态:
systemctl --user status weather-fetcher.service
如果你希望这个服务在你每次登录时自动启动,你需要启用它:
systemctl --user enable weather-fetcher.service
就这样,你的个人服务就跑起来了。管理起来也比以前那些复杂的脚本方便太多了。
我发现
systemctl --user
cron
systemctl --user
nohup
screen
tmux
systemctl --user
systemctl --user
cron
systemctl --user
Timer
cron
systemctl --user
总的来说,任何需要在你登录后自动运行、保持后台运行、并且不需要系统级权限的个人应用程序或脚本,都可以考虑用
systemctl --user
以上就是如何在Linux中用户服务 Linux systemctl用户模式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号