CentOS关机/重启前自动运行命令


=Start=

缘由:

当系统上搭建了一个WordPress这样的博客时,如果贸然关机/重启系统,可能导致MySQL数据库出错,从而无法正常启动,所以,需要在系统关机/重启的时候添加一个trigger用于先优雅的关闭MySQL/Nginx/php-fpm等服务,然后关机。

在此需求中,CentOS 6 和 7 是有区别的,因为 SysV 和 systemd 的不同而导致。

正文:

参考解答:
# 查看系统当前的运行级别
$ runlevel
N 3
$ who -r
         运行级别 3 2017-01-12 20:09
$ chkconfig #在CentOS 7上执行的效果
注意:该输出结果只显示 SysV 服务,并不包含原生 systemd 服务。SysV 配置数据可能被原生 systemd 配置覆盖。
      如果您想列出 systemd 服务,请执行 'systemctl list-unit-files'
      欲查看对特定 target 启用的服务请执行
      'systemctl list-dependencies [target]'
netconsole      0:关 1:关 2:关 3:关 4:关 5:关 6:关
network         0:关 1:关 2:开 3:开 4:开 5:开 6:关
$
CentOS 6

按照 http://unix.stackexchange.com/questions/48973/execute-a-command-before-shutdown/48974#48974 上面讲的方法,测试失败!

First write your script, store it in /etc/init.d/ ;
then create a symlink in each of /etc/rc0.d and /etc/rc6.d (if you want both) pointing to your script.
# vim /etc/init.d/custom_test   #脚本格式需要类似于 http://www.centoscn.com/CentOS/2014/0921/3798.html 里面说的那样,可以从 /etc/init.d 中复制一个其它的文件然后进行简单修改即可
echo "`whoami` exec @(`date +%s`) before stop" >> /tmp/abcxyz
# ln -s /etc/init.d/custom_test /etc/rc0.d/K00custom_test
# ln -s /etc/init.d/custom_test /etc/rc6.d/K00custom_test
CentOS 7

按照 http://unix.stackexchange.com/questions/48973/execute-a-command-before-shutdown/294539#294539 上面讲的方法,测试成功!

# vim /usr/lib/systemd/system/custom_test.service #编写对应的.service文件
[Unit]
Description=Exec @ Reboot
#DefaultDependencies=no
#Requires=shutdown.target reboot.target halt.target
#Before=shutdown.target reboot.target halt.target
#After=shutdown.target reboot.target halt.target
[Service]
Type=oneshot
RemainAfterExit=true
#ExecStart=/etc/init.d/custom_start
ExecStop=/etc/init.d/custom_shutdown
[Install]
WantedBy=multi-user.target
# systemctl enable custom_test #启用编辑好的.service
参考链接:

=END=

,

《“CentOS关机/重启前自动运行命令”》 有 1 条评论

  1. 方法一:
    `
    ####
    # vim /usr/lib/systemd/system/custom_shutdown.service
    [Unit]
    Description=Exec before Shutdown/Reboot/Halt
    DefaultDependencies=no
    #Requires=shutdown.target reboot.target halt.target
    Before=shutdown.target reboot.target halt.target
    #After=shutdown.target reboot.target halt.target

    [Service]
    Type=oneshot
    RemainAfterExit=true
    #ExecStart=/etc/init.d/custom_start
    ExecStop=/etc/init.d/custom_shutdown

    [Install]
    # WantedBy=multi-user.target
    WantedBy=shutdown.target reboot.target halt.target
    ####

    ####
    # vim /etc/init.d/custom_shutdown
    #!/bin/bash
    # Stop Nginx/php-fpm/MySQL before Shutdown/Reboot/Halt
    systemctl stop nginx
    systemctl stop php-fpm
    systemctl stop mysqld
    ####

    ####
    # systemctl enable custom_shutdown
    ####
    `

    方法二:
    将 shutdown/reboot/halt 等命令用 `alias` 增加一些功能,比如先平稳关闭Nginx/php-fpm/MySQL然后再关机。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注