码迷,mamicode.com
首页 > 其他好文 > 详细

CentOS6和CentOS7服务开机启动

时间:2016-02-26 22:11:24      阅读:289      评论:0      收藏:0      [点我收藏+]

标签:

CentOS 6和CentOS 7都可以定义开机启动哪些服务,但CentOS 6的命令是chkconfig,CentOS 7是systemctl。

本文将介绍两种命令的实现方式。

一、CentOS 6的服务

在CentOS 6下编写一个服务http,位于/etc/init.d目录下,具体的脚本如下:

#!/bin/bash
# chkconfig: 2345 10 90 
# description: http ....

start() {
  echo "HTTP is enabled now"
}
stop() {
  echo "HTTP is disable now"
}
case "$1" in
start)
  start
  ;;
stop)
  stop
  ;;
restart)
  start
  stop
  ;;
*)
  echo "USAGE $0 {start|stop|restart}"
  exit
esac

注意,两个注释"# chkconfig: 2345 10 90"和 "# description: http ...."表示:启动的level和优先级,已经服务的描述。这两段注释是一定要加上的。否则服务添加是报错。

通过如下命令实现把服务注册到chkconfig中:

chkconfig --add http

然后可以通过:

chkconfig http on

定义开机启动这个服务。另外可以查看chkconfig的状态:

chkconfig --list

 

 

二、CentOS 7的服务

在CentOS 7的机器中创建一个服务的脚本: /etc/init.d/myuptime。具体的脚本如下:

#!/bin/bash

start() {
  echo starting
  while true
  do
    uptime >> /root/myuptime.txt
    sleep 2
  done
}
stop() {
  echo stoping
  pid=`ps -ef | grep myuptime | grep -v grep | awk {print $2}`
  kill $pid &
}
case "$1" in
start)
  start
  ;;
stop)
  stop
  ;;
*)
  echo "USAGE $0 {start|stop|restart}"
  exit
esac

在/etc/systemd/system中创建服务描述文件myuptime.service

[Unit]
Description=uptime Service
After=network.target

[Service]
Type=simple
User=root
ExecStart=/etc/init.d/myuptime start
ExecStop=/etc/init.d/myuptime stop

[Install]
WantedBy=multi-user.target

这个文件中包含Unit、Service和Install三个部分。定义了描述、服务属性的类型和安装参数等。其中ExecStart、ExecStop定义了启动和停止的实现方式。

配置好后,运行:

[root@hwcentos70-01 system]#systemctl enable myuptime

ln -s /etc/systemd/system/myuptime.service /etc/systemd/system/multi-user.target.wants/myuptime.service

systemctl把myuptime服务加入到了启动项目中。

执行:

[root@hwcentos70-01 system]#systemctl start myuptime

查看:

[root@hwcentos70-01 system]#systemctl status myuptime

myuptime.service - uptime Service

Loaded: loaded (/etc/systemd/system/myuptime.service; enabled)

Active: active (running) since Fri 2016-02-26 13:37:23 UTC; 10s ago

Main PID: 53620 (myuptime)

CGroup: /system.slice/myuptime.service

├─53620 /bin/bash /etc/init.d/myuptime start

└─53632 sleep 2

 

Feb 26 13:37:23 hwcentos70-01 systemd[1]: Started uptime Service.

Feb 26 13:37:23 hwcentos70-01 myuptime[53620]: starting

通过以上的方法实现把myuptime作为服务加入启动项。

CentOS6和CentOS7服务开机启动

标签:

原文地址:http://www.cnblogs.com/hengwei/p/5221888.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!