Linux 开机自启动

Linux 系统启动时,内核首先启动用户空间第一个进程 PID 1,即初始化系统(init system)。历史上常见实现包括 SysVinit、Upstart 和 systemd。初始化系统负责根据配置和依赖关系启动系统组件。之后,任何已启动的进程都可以在权限允许的情况下创建新的子进程,因此系统中的程序启动来源并不局限于 init system,例如桌面环境、cron、supervisor 等都可能成为程序启动入口。

Linux 中常见的程序自动启动方式主要包括:

  1. systemd 服务:用于系统服务和后台进程管理;
  2. 桌面环境自启动:用户登录图形桌面后启动应用;
  3. 定时任务:通过 cron 或 systemd timer 按时间启动任务;
  4. 登录脚本:通过 shell profile 等方式在用户登录时执行。

Systemd

PS:截止到 2026 年,除了少数发行版和部分老版本 Linux(如 CentOS 6、Debian 7 及更早版本)使用源自 UNIX System V 的 SysVinit,绝大多数主流 Linux 发行版已经采用 Systemd 作为初始化系统(兼容 SysVinit)。Ubuntu 比较另类的一点是从 6 ~ 14 一直采用的是 Canonical 自研的 Upstart(兼容 SysVinit),最终没有竞争过红帽家的 Systemd,从 15 开始转 Systemd 阵营。
在 Linux 社区,对 Systemd 最主要的批评之一,是它被认为违反了 Unix 的设计哲学——"Do one thing and do it well"。SysVinit 只有几万行代码,本质上只是负责按顺序执行启动脚本,而 Systemd 整个项目的代码规模达到数百万行,除了初始化系统,还集成了日志、登录管理、DNS、网络、定时器等众多功能。因此,不少开发者认为,它已经不仅仅是一个 init 系统,而更像是一个覆盖系统多个基础设施的框架。

-> % cat /etc/systemd/system/multi-user.target.wants/cron.service
[Unit]
Description=Regular background program processing daemon
Documentation=man:cron(8)
After=remote-fs.target nss-user-lookup.target

[Service]
EnvironmentFile=-/etc/default/cron
ExecStart=/usr/sbin/cron -f -P $EXTRA_OPTS
IgnoreSIGPIPE=false
KillMode=process
Restart=on-failure
SyslogFacility=cron

[Install]
WantedBy=multi-user.target
# 查看所有开机启动的服务:
-> % systemctl list-unit-files --state=enabled

# 查看正在运行的服务:
-> % systemctl --type=service --state=running

# 查看某个服务是否开机启动:
-> % systemctl is-enabled cron
enabled

列出 Systemd 定时任务:

-> % systemctl list-timers
NEXT                            LEFT LAST                              PASSED UNIT                           ACTIVATES
Wed 2026-07-15 12:50:00 CST     9min Wed 2026-07-15 12:40:00 CST      56s ago sysstat-collect.timer          sysstat-collect.service
Wed 2026-07-15 13:04:57 CST    23min Wed 2026-07-15 12:32:54 CST     8min ago fwupd-refresh.timer            fwupd-refresh.service
Wed 2026-07-15 13:32:44 CST    51min Wed 2026-07-15 12:34:02 CST     6min ago anacron.timer                  anacron.service
Wed 2026-07-15 14:32:24 CST 1h 51min Wed 2026-07-15 11:32:24 CST  1h 8min ago apport-autoreport.timer        apport-autoreport.service
Wed 2026-07-15 16:23:05 CST 3h 42min Wed 2026-07-15 05:50:18 CST            - motd-news.timer                motd-news.service
Wed 2026-07-15 16:50:48 CST  4h 9min Wed 2026-07-15 10:38:46 CST  2h 2min ago ua-timer.timer                 ua-timer.service
Thu 2026-07-16 00:00:00 CST      11h Wed 2026-07-15 00:00:00 CST            - dpkg-db-backup.timer           dpkg-db-backup.service
Thu 2026-07-16 00:00:00 CST      11h Wed 2026-07-15 00:00:00 CST            - privoxy-cleanup.timer          privoxy-cleanup.service
Thu 2026-07-16 00:00:00 CST      11h -                                      - sysstat-rotate.timer           sysstat-rotate.service
Thu 2026-07-16 00:07:00 CST      11h -                                      - sysstat-summary.timer          sysstat-summary.service
Thu 2026-07-16 00:30:52 CST      11h Wed 2026-07-15 00:29:04 CST            - plocate-updatedb.timer         plocate-updatedb.service
Thu 2026-07-16 00:39:05 CST      11h Wed 2026-07-15 00:29:04 CST            - logrotate.timer                logrotate.service
Thu 2026-07-16 01:57:49 CST      13h Wed 2026-07-15 06:06:45 CST            - apt-daily.timer                apt-daily.service
Thu 2026-07-16 05:50:05 CST      17h Wed 2026-07-15 06:54:49 CST            - man-db.timer                   man-db.service
Thu 2026-07-16 06:07:09 CST      17h Wed 2026-07-15 06:47:46 CST            - apt-daily-upgrade.timer        apt-daily-upgrade.service
Thu 2026-07-16 10:37:23 CST      21h Wed 2026-07-15 10:37:23 CST  2h 3min ago update-notifier-download.timer update-notifier-download.service
Thu 2026-07-16 10:47:22 CST      22h Wed 2026-07-15 10:47:22 CST 1h 53min ago systemd-tmpfiles-clean.timer   systemd-tmpfiles-clean.service
Sat 2026-07-18 06:10:20 CST   2 days Tue 2026-07-07 20:21:04 CST            - update-notifier-motd.timer     update-notifier-motd.service
Sun 2026-07-19 03:10:35 CST   3 days Sun 2026-07-12 03:10:22 CST            - e2scrub_all.timer              e2scrub_all.service
Mon 2026-07-20 00:21:23 CST   4 days Mon 2026-07-13 01:29:24 CST            - fstrim.timer                   fstrim.service

20 timers listed.
Pass --all to see loaded but inactive timers, too.

-> % cat /etc/systemd/system/timers.target.wants/anacron.timer
[Unit]
Description=Trigger anacron every hour

[Timer]
OnCalendar=*-*-* 07..23:30
RandomizedDelaySec=5m
Persistent=true

[Install]
WantedBy=timers.target
  • 单调定时器:OnActiveSec=, OnBootSec=, OnStartupSec=, OnUnitActiveSec=, OnUnitInactiveSec=
  • 日历定时器:OnCalendar 完整格式:

    DayOfWeek Year-Month-Day Hour:Minute:Second
    

更多选项可以参考:金步国 systemd.timer 中文手册

桌面环境自动启动

systemd -> gdm3 (显示管理器) -> gnome-session -> GNOME Session Manager -> 读取 ~/.config/autostart/*.desktop
-> % find ~/.config/autostart -type f
/home/catroll/.config/autostart/com.github.hluk.copyq.desktop
/home/catroll/.config/autostart/remmina-applet.desktop.save
/home/catroll/.config/autostart/remmina-applet.desktop
/home/catroll/.config/autostart/nutstore-daemon.desktop
-> % ps -ef | grep remmina | grep -Fv grep
catroll     5357    4639  0 10:34 ?        00:00:00 /usr/bin/remmina -i
-> % ps -fp 4639
UID          PID    PPID  C STIME TTY          TIME CMD
catroll     4639       1  0 10:34 ?        00:00:00 /usr/lib/systemd/systemd --user

定时任务

cron 这个命令自 Unix 系统开始开发就存在。
后来被广泛采纳的是 Paul Vixie 开发的版本,被称之为 Vixie Cron

  • /etc/crontab
  • /etc/cron.d
  • 支持分钟级调度

配置格式就是大家熟悉的:

  * * * * * <command to execute>
# | | | | |
# | | | | day of the week (0–6) (Sunday to Saturday;
# | | | month (1–12)             7 is also Sunday on some systems)
# | | day of the month (1–31)
# | hour (0–23)
# minute (0–59)

Vixie Cron 有两个影响大的分叉:

  • 红帽系:Cronie

    [root@iZt4nerpnxvn37c1tlx3brZ ~]# yum list --installed | grep cron
    cronie.x86_64                          1.5.7-15.el9                   @System
    cronie-anacron.x86_64                  1.5.7-15.el9                   @System
    crontabs.noarch                        1.11-27.20190603git.el9        @System
    
  • Debian 系:Debian cron

    -> % apt list --installed | grep cron
    anacron/resolute,now 2.3-45ubuntu1 amd64 [installed]
    cron-daemon-common/resolute,now 3.0pl1-200ubuntu1 all [installed,automatic]
    cron/resolute,now 3.0pl1-200ubuntu1 amd64 [installed,automatic]
    

简单使用没有什么太大区别。
值得注意的是,anacron 也是 cronie 项目组维护,所以在红帽系 anacron 的包名是 cronie-anacron。

anacron 也是一个知名的定时任务工具,它不是用来取代 cron,而是作为 cron 的补充机制。
按照 cron 的设计,任务会在预定时间点执行;如果系统在该时间点处于关机状态,任务就会被直接跳过,不会补执行。例如,将备份任务设置为每天凌晨 0 点执行,如果电脑在 23:59 关机、00:01 开机,那么当天的备份就会被错过。
对于服务器而言,这通常不是问题,因为服务器很少关机;但对于个人电脑、笔记本等经常关机或休眠的设备,这种情况十分常见。anacron 的作用就是记录这些周期性任务是否已经执行,如果发现因为关机而错过了执行时机,就会在系统下次启动后适时补执行一次,从而保证每天、每周或每月的维护任务不会遗漏。

anacron 并不支持分钟级调度,它主要面向 daily、weekly、monthly 等周期性任务。
比如:/etc/anacrontab

#period in days   delay in minutes   job-identifier   command
1   5   cron.daily      nice run-parts /etc/cron.daily
7   25  cron.weekly     nice run-parts /etc/cron.weekly
@monthly 45 cron.monthly        nice run-parts /etc/cron.monthly

这里面就是定义了三条补救策略。

参考:Linux 定时任务(cron/crontab)

登录脚本

登录脚本(Login Script)本质上就是 Shell 在用户登录时自动执行的脚本。如果在这些脚本中启动程序,那么程序就会随着登录自动启动。
需要注意的是,登录脚本属于 Shell 的机制,而不是 Linux 内核或 systemd,因此具有以下特点:

  1. 只有启动 Login Shell 时才会执行。
  2. 每次启动 Login Shell 都会执行,因此使用这种方式实现自启动时,需要自行处理程序重复启动的问题。
  3. 不同 Shell(如 Bash、Zsh)使用的登录脚本不同,配置方法略有差异。
  4. 图形登录是否会执行登录脚本,取决于登录管理器(Display Manager)和桌面会话的具体实现,不同发行版和桌面环境可能存在差异。
  5. 没有生命周期管理能力,程序退出后不会自动重启,也无法方便地控制依赖关系和启动顺序。

注意: ~/.bashrc非 Login Shell 的初始化脚本。如果在其中启动程序,那么每打开一个新的 Bash 终端都会再次执行一次,因此通常不适合作为程序自启动的配置文件。

例如使用 Bash:

用户登录
    │
    ▼
bash
    │
    ├── /etc/profile
    ├── ~/.bash_profile
    ├── ~/.bash_login
    ├── ~/.profile
    └── 执行其中的命令

如果这些文件中有:

~/bin/my-agent &

那么登录后就会自动启动 my-agent

# find ~/.*profile* ~/.bash* /etc/profile* -type f | sort -u
/etc/profile
/etc/profile.d/bash_completion.sh
/etc/profile.d/colorgrep.csh
/etc/profile.d/colorgrep.sh
/etc/profile.d/colorls.csh
/etc/profile.d/colorls.sh
/etc/profile.d/colorsysstat.csh
/etc/profile.d/colorsysstat.sh
/etc/profile.d/colorxzgrep.csh
/etc/profile.d/colorxzgrep.sh
/etc/profile.d/colorzgrep.csh
/etc/profile.d/colorzgrep.sh
/etc/profile.d/csh.local
/etc/profile.d/debuginfod.csh
/etc/profile.d/debuginfod.sh
/etc/profile.d/gawk.csh
/etc/profile.d/gawk.sh
/etc/profile.d/lang.csh
/etc/profile.d/lang.sh
/etc/profile.d/less.csh
/etc/profile.d/less.sh
/etc/profile.d/sh.local
/etc/profile.d/which2.csh
/etc/profile.d/which2.sh
/root/.bash_history
/root/.bash_logout
/root/.bash_profile
/root/.bashrc
如果你有魔法,你可以看到一个评论框~