【发布时间】:2011-08-16 14:58:16
【问题描述】:
有什么方法可以在 Linux 启动时添加应用程序/脚本,以便每次系统启动时都会执行?
我正在寻找一些自动化的方式,即用户不应该通过 cron 作业或类似的方式添加它。
【问题讨论】:
-
如果是 ubuntu 就用 $ gnome-session-properties
标签: linux
有什么方法可以在 Linux 启动时添加应用程序/脚本,以便每次系统启动时都会执行?
我正在寻找一些自动化的方式,即用户不应该通过 cron 作业或类似的方式添加它。
【问题讨论】:
标签: linux
【讨论】:
/etc/cron.d,或在他们不知情的情况下从您的程序中调用 crontab。
除了系统级启动脚本之外,您的桌面环境可能还有自己的自动运行程序的方式。文件夹.config/autostart 应该是定义自动运行条目的桌面中立方式。 /etc/xdg/autostart 用于系统范围的配置。 http://developer.gnome.org/autostart-spec/ 上有关规范的详细信息。
对于 LXDE 的自动启动条目也可以在~/.config/lxsession/LXDE/autostart 中设置。
如果您需要在网络启动并运行之后运行脚本,情况会有所不同。在这种情况下,您应该检查可以为您的网络管理员定义的特殊连接后脚本。 NetworkManager 和 wicd 都有自己的方式来指定连接后自动运行条目。如果网络是通过ifupdown 配置的,那么后期脚本可以放在/etc/network/if-up.d/ 文件夹中。但是运行连接后脚本的更好方法可能是 systemd(对于支持它的系统,这是大多数现代发行版)。
如果您要自动启动的东西不是需要桌面的图形应用程序,那么最好避免使用 xorg 或您当前桌面环境提供的任何自动启动工具。
systemd 已在许多现代发行版中无处不在,它在服务的启动方式和运行方式方面提供了很多控制和灵活性。
我将总结一些好处(systemd can do a lot more):
User=myuser
Restart=on-failure|on-watchdog|on-abnormal|always
Type=simple|forking|oneshot|notify|dbus
[Unit] 部分中的Wants=network-online.target)。启动 telegram-cli 守护进程的示例服务。把它放在/etc/systemd/system/tg.service。
[Unit]
Description=MyDaemon
Wants=network-online.target
After=network-online.target
[Service]
ExecStart=/usr/local/bin/telegram-cli -k /etc/telegram-cli/tg-server.pub -W -P 1234 -d -vvvRC
ExecStop=/usr/bin/pkill -f telegram-cli
User=jicu
[Install]
WantedBy=multi-user.target
现在您可以启用服务自动启动:
sudo systemctl enable tg
启动服务:
sudo systemctl start tg
停止服务:
sudo systemctl stop tg
查看状态:
systemctl status tg
禁用服务:
sudo systemctl disable tg
为了节省您的额外输入,您可以在 ~/.bashrc 中添加 alias sc='sudo systemctl $*' 行,然后您就可以将上面的命令缩短为例如sc start tg.
注意:如果您使用过
cron,那么请注意 crontab 条目是在受限环境中运行的——systemd同样适用:始终使用绝对路径,并且不假设任何变量是定义。显式设置脚本所依赖的任何变量。systemd不会使用您用户的.bashrc和$PATH。
更多信息:
【讨论】:
是的,可以通过在rc.local 中定义位于/etc 或/etc/rc.d 目录中的可执行文件的路径来在Linux 上启动时运行程序,例如:
#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.
touch /var/lock/subsys/local
/path/to/executable
注意:不要忘记分配文件文档中描述的可执行权限,即Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure that this script will be executed during boot.
【讨论】:
cron 调度程序是您的朋友。
Startup applications
Add
Startup command box输入命令OK(您应该会在列表中看到您的新命令)Close
通过重新启动或注销并重新登录进行测试。
来源:https://help.ubuntu.com/community/AddingProgramToSessionStartup
【讨论】:
每个发行版都使用各自的引导技术,因此需要查看您发行版的文档。 /etc/rc.local 是一个可以放一些自动化脚本的地方,但它确实已经过时了。现在大多数基于 linux 的系统都使用运行级别或 systemd 引导,因此大多数自动启动的作业都可以进行精细控制。
【讨论】:
我在这里找到了答案: https://stackoverflow.com/questions/7221757/run-automatically-program-on-startup-under-linux-ubuntu 在我的 Linux Ubuntu 12.10 会话中,我能够创建一个文件/脚本来关闭我的触控板。
【讨论】: