Menu

  • Home
  • Work
    • Cloud
      • Virtualization
      • IaaS
      • PaaS
    • Java
    • Go
    • C
    • C++
    • JavaScript
    • PHP
    • Python
    • Architecture
    • Others
      • Assembly
      • Ruby
      • Perl
      • Lua
      • Rust
      • XML
      • Network
      • IoT
      • GIS
      • Algorithm
      • AI
      • Math
      • RE
      • Graphic
    • OS
      • Linux
      • Windows
      • Mac OS X
    • BigData
    • Database
      • MySQL
      • Oracle
    • Mobile
      • Android
      • IOS
    • Web
      • HTML
      • CSS
  • Life
    • Cooking
    • Travel
    • Gardening
  • Gallery
  • Video
  • Music
  • Essay
  • Home
  • Work
    • Cloud
      • Virtualization
      • IaaS
      • PaaS
    • Java
    • Go
    • C
    • C++
    • JavaScript
    • PHP
    • Python
    • Architecture
    • Others
      • Assembly
      • Ruby
      • Perl
      • Lua
      • Rust
      • XML
      • Network
      • IoT
      • GIS
      • Algorithm
      • AI
      • Math
      • RE
      • Graphic
    • OS
      • Linux
      • Windows
      • Mac OS X
    • BigData
    • Database
      • MySQL
      • Oracle
    • Mobile
      • Android
      • IOS
    • Web
      • HTML
      • CSS
  • Life
    • Cooking
    • Travel
    • Gardening
  • Gallery
  • Video
  • Music
  • Essay

Linux运行级别和启动顺序

5
Apr
2012

Linux运行级别和启动顺序

By Alex
/ in Linux
/ tags Linux知识, SystemV
0 Comments

本文主要介绍Sysvinit初始化系统,牵涉到一部分upstart的知识。参考Linux的三种Init机制详细的了解Linux系统的初始化机制。

运行级别
标准的Linux运行级别定义
一共有7个运行级别:
运行级别 说明
0  停机,机器关闭
1  单用户模式
2  没有用到/可以用户自定义
3  完全多用户模式,没有图形界面
4  没有用到/可以用户自定义
5  完全多用户模式,有图形界面
6  重新启动
Debian及其衍生的系统(例如Ubuntu)运行级别定义
一共有7个运行级别,但是2-5没有区别
运行级别 说明
0  停机,机器关闭
1  单用户模式
2  完全多用户模式,有图形界面
3  完全多用户模式,有图形界面
4  完全多用户模式,有图形界面
5  完全多用户模式,有图形界面
6  重新启动
检查和修改系统的默认运行级别
Shell
1
2
3
4
5
6
7
8
9
10
11
#查看运行级别命令
runlevel
 
#修改运行级别
sudo vi /etc/inittab
#添加以下内容,则默认运行级别修改3
id:3:initdefault:
#重启后,再使用命令runlevel查看,会发现运行级别变成了3
 
#下面是个非主流重启操作
sudo init 6
不同运行级别到底有什么区别

不同运行级别,会执行不同的脚本,这些脚本是在:/etc/rc0.d 到 /etc/rc5.d这些目录中定义的,目录名中的数字和运行级别对应。
这些脚本都是指向/etc/init.d/下文件的符号连接。如果你留意的话,发现这些脚本均是以如下方式命名:

前缀 两位数字 脚本名称
可以是K或者S 表示脚本被执行的顺序 /etc/init.d中对应脚本的名称

例如:S91apache2、K09apache2等。

前缀S或者K表示启动或者停止某个服务。分别会调用init.d下脚本的do_start()、do_stop()函数。

如果要在运行级别N下禁用服务myservice,则只需要删除rcN.d中删除符号连接,例如:

Shell
1
2
3
4
#进入运行级别2的目录
cd /etc/rc2.d
#修改前缀S为K
rm S11myservice
自定义服务

Linux下的 service 命令可以用于启动或者停止一个服务,该命令会忽略大部分环境变量,并且设置工作目录为 / 。

该命令的本质执行以下二者之一:

  1. 执行位于/etc/init.d/下的System V init script
  2. 执行位于/etc/init/下的启动任务(upstart job)
System V init脚本模板

因此,我们只需要编写符合规范的脚本,并按照上一节描述的命名规则放置到对应位置,即可自己定义“服务”,下面是Ubuntu 14的System V init脚本的模板:

Shell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#! /bin/sh
### BEGIN INIT INFO
# Provides:          Sample daemon
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: System V init script  example
# Description:       System V init script  example
### END INIT INFO
 
#注意,上面的INIT INFO会被chkconfig命令读取,自动完成/etc/rc*.d中符号链接的更新
# Author: Alex Wang
 
 
# 如当前服务在mountnfs.sh后运行,PATH只应当包含/usr/*下的内容
PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin
DESC="System V init script  example"
NAME=smpld
# 守护程序的路径
DAEMON=/usr/local/bin/$NAME
DAEMON_ARGS="--msg HelloWorld"
#写入进程ID的文件
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME
 
# 如果守护程序不可执行,则退出
[ -x "$DAEMON" ] || exit 0
 
# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME
 
# 加载rcS变量
. /lib/init/vars.sh
 
# 执行此文件以定义LSB log_*函数
. /lib/lsb/init-functions
 
#
# 用于启动(S)守护程序/服务的函数
#
do_start()
{
    # 返回值说明:
    #   0 守护程序启动成功
    #   1 守护程序(在此函数执行之前)已经启动
    #   2 守护程序无法启动
    # 一般使用start-stop-daemon来进行守护程序的启动与关闭
    # 测试守护程序是否已经被启动
    #   start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null || return 1
    # 尝试启动守护程序
    #   start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- $DAEMON_ARGS || return 2
    # 添加额外的代码,例如等待进程准备好提供服务,或者仅仅是等待一段时间。等待以便依赖于此守护程序的其它Daemon能够启动
    $DAEMON $DAEMON_ARGS
}
 
#
# 用于停止(K)守护程序/服务的函数
#
do_stop()
{
    # 返回值说明:
    #   0 守护程序停止成功
    #   1 守护程序(在此函数执行之前)已经停止
    #   2 守护程序无法停止
    #   其它值:有错误发生
    # 一般使用start-stop-daemon来进行守护程序的启动与关闭
    #   start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME
    #   RETVAL="$?"
    #   [ "$RETVAL" = 2 ] && return 2
    #
    # 等待守护程序fork出的子进程停止:
    #   start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON
    #    [ "$?" = 2 ] && return 2
    # 某些守护程序不会删除其PID文件,需要手工删除
    #  rm -f $PIDFILE
    #  return "$RETVAL"
}
 
#
# 用户发送SIGHUP信号给守护程序的函数
#
do_reload() {
    # start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME
    return 0
}
 
#根据第一个参数是start、stop、reload……,执行不同的函数
case "$1" in
  start)
    [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
    do_start
    case "$?" in
        0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
        2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
    esac
    ;;
  stop)
    [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
    do_stop
    case "$?" in
        0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
        2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
    esac
    ;;
  status)
    status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $?
    ;;
  reload|force-reload)
 
    log_daemon_msg "Reloading $DESC" "$NAME"
    do_reload
    log_end_msg $?
    ;;
  restart|force-reload)
    log_daemon_msg "Restarting $DESC" "$NAME"
    do_stop
    case "$?" in
      0|1)
        do_start
        case "$?" in
            0) log_end_msg 0 ;;
            1) log_end_msg 1 ;; # 旧的进程仍然在运行
            *) log_end_msg 1 ;; # 启动失败
        esac
        ;;
      *)
        # Failed to stop
        log_end_msg 1
        ;;
    esac
    ;;
  *)
    echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2
    exit 3
    ;;
esac
#空命令,返回0
:
System V init脚本样例

下面是实际中的一个具体例子:

tomcat7d
Shell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#! /bin/sh
### BEGIN INIT INFO
# Provides:          tomcat7d
# Required-Start:    $syslog
# Required-Stop:     $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Gmem tomcat7d daemon
# Description:       Gmem tomcat7d daemon
### END INIT INFO
 
# Author: Alex Wang
 
export PDT_DIR=/usr/local/Tomcat7
. $PDT_DIR/setenv.sh
LOG_FILE=$LOG_DIR/tomcat7d.log
touch $LOG_FILE
do_log()
{
    echo `date "+%Y-%m-%d %H:%M:%S"` $1 >> $LOG_FILE
    echo $1
}
 
do_start()
{    
    ps -fC "mysqld_safe" | grep "$PDT_DIR/db/my.cnf" > /dev/null
    if [[ $? -eq 0 ]]; then
        do_log "$PDT_NAME database service is already up."
    else
        do_log "Starting $PDT_NAME database service..."
        $PDT_DIR/startup-db.sh
    fi
      
    ps -fC "java"  | grep "$PDT_DIR/jre/bin/java" > /dev/null
    if [[ $? -eq 0 ]]; then
        do_log "$PDT_NAME application service is already up."
    else
        do_log "Starting $PDT_NAME application service..."
        $PDT_DIR/startup-app.sh
    fi
    
    return 0
}
 
do_stop()
{
    ps -fC "mysqld_safe" | grep "$PDT_DIR/db/my.cnf" > /dev/null
    if [[ $? -eq 0 ]]; then
        do_log "Stopping $PDT_NAME database service..."
        $PDT_DIR/db/bin/mysqladmin -uroot -hlocalhost --protocol=tcp shutdown
        do_log "$PDT_NAME database service stopped."
    else
        do_log "$PDT_NAME database service is already down."
    fi
      
    ps -fC "java"  | grep "$PDT_DIR/jre/bin/java" > /dev/null
    if [[ $? -eq 0 ]]; then
        do_log "Stopping $PDT_NAME application service..."
        $PDT_DIR/bin/shutdown.sh
        do_log "$PDT_NAME application service stopped."
    else
        do_log "$PDT_NAME application service is already down."
    fi
    
    return 0
}
 
case "$1" in
  start)
  do_start
  ;;
  stop)
  do_stop
  ;;
  restart)
  do_stop
  do_start
  ;;
esac
 
:
#该脚本放置于/etc/init.d下
#执行命令: chkconfig --add tomcat7d 即可注册服务
注册服务

命令 chkconfig 用于配置系统启动时服务的行为,新近的Ubuntu版本已经不支持该命令,使用 update-rc.d 命令代替之:

Shell
1
sudo update-rc.d myservice defaults
启动脚本rc.local

在Ubuntu下,你可能会注意到rc2.d - rc5.d里面有一个数字最大的S99rc.local文件,查看其链接目标/etc/init.d/rc.local ,可以看到类似如下脚本:

Shell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#! /bin/sh
### BEGIN INIT INFO
# Provides:          rc.local
# Required-Start:    $all
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Run /etc/rc.local if it exist
### END INIT INFO
 
 
PATH=/sbin:/usr/sbin:/bin:/usr/bin
 
. /lib/init/vars.sh
. /lib/lsb/init-functions
 
do_start() {
    if [ -x /etc/rc.local ]; then
            [ "$VERBOSE" != no ] && log_begin_msg "Running local boot scripts (/etc/rc.local)"
        /etc/rc.local
        ES=$?
        [ "$VERBOSE" != no ] && log_end_msg $ES
        return $ES
    fi
}
 
case "$1" in
    start)
    do_start
        ;;
    restart|reload|force-reload)
        echo "Error: argument '$1' not supported" >&2
        exit 3
        ;;
    stop)
        ;;
    *)
        echo "Usage: $0 start|stop" >&2
        exit 3
        ;;
esac

在执行S操作的时候,/etc/init.d/rc.local 会调用脚本/etc/rc.local,我们常常用这个脚本来执行一些操作:这些操作在所有系统服务启动完毕后执行。

Linux系统启动时执行脚本的整体步骤

脚本执行由 init 进程发起,以Ubuntu为例,步骤如下:

  1. /etc/init/ 目录下的所有*.conf文件被执行,这些文件可能具有类似如下的内容:
    Shell
    1
    2
    3
    4
    5
    6
    7
    8
    9
    description     "deferred execution scheduler"
    #启动的时机,可能是运行级别(runlevel)、文件系统(filesystem)等
    start on runlevel [2345]
    stop on runlevel [!2345]
     
    expect fork
    respawn
     
    exec atd
  2. /etc/rc*.d/ 目录下的脚本,按照顺序执行
  3. /etc/rc.local 脚本被执行
← TCP/IP协议栈学习笔记
使用Java进行网络编程 →

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Related Posts

  • Linux的三种Init机制
  • Linux命令知识集锦
  • Linux信号、进程和会话
  • Linux网络知识集锦
  • Linux知识集锦

Recent Posts

  • Investigating and Solving the Issue of Failed Certificate Request with ZeroSSL and Cert-Manager
  • A Comprehensive Study of Kotlin for Java Developers
  • 背诵营笔记
  • 利用LangChain和语言模型交互
  • 享学营笔记
ABOUT ME

汪震 | Alex Wong

江苏淮安人,现居北京。目前供职于腾讯云,专注容器方向。

GitHub:gmemcc

Git:git.gmem.cc

Email:gmemjunk@gmem.cc@me.com

ABOUT GMEM

绿色记忆是我的个人网站,域名gmem.cc中G是Green的简写,MEM是Memory的简写,CC则是我的小天使彩彩名字的简写。

我在这里记录自己的工作与生活,同时和大家分享一些编程方面的知识。

GMEM HISTORY
v2.00:微风
v1.03:单车旅行
v1.02:夏日版
v1.01:未完成
v0.10:彩虹天堂
v0.01:阳光海岸
MIRROR INFO
Meta
  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org
Recent Posts
  • Investigating and Solving the Issue of Failed Certificate Request with ZeroSSL and Cert-Manager
    In this blog post, I will walk ...
  • A Comprehensive Study of Kotlin for Java Developers
    Introduction Purpose of the Study Understanding the Mo ...
  • 背诵营笔记
    Day 1 Find Your Greatness 原文 Greatness. It’s just ...
  • 利用LangChain和语言模型交互
    LangChain是什么 从名字上可以看出来,LangChain可以用来构建自然语言处理能力的链条。它是一个库 ...
  • 享学营笔记
    Unit 1 At home Lesson 1 In the ...
  • K8S集群跨云迁移
    要将K8S集群从一个云服务商迁移到另外一个,需要解决以下问题: 各种K8S资源的迁移 工作负载所挂载的数 ...
  • Terraform快速参考
    简介 Terraform用于实现基础设施即代码(infrastructure as code)—— 通过代码( ...
  • 草缸2021
    经过四个多月的努力,我的小小荷兰景到达极致了状态。

  • 编写Kubernetes风格的APIServer
    背景 前段时间接到一个需求做一个工具,工具将在K8S中运行。需求很适合用控制器模式实现,很自然的就基于kube ...
  • 记录一次KeyDB缓慢的定位过程
    环境说明 运行环境 这个问题出现在一套搭建在虚拟机上的Kubernetes 1.18集群上。集群有三个节点: ...
  • eBPF学习笔记
    简介 BPF,即Berkeley Packet Filter,是一个古老的网络封包过滤机制。它允许从用户空间注 ...
  • IPVS模式下ClusterIP泄露宿主机端口的问题
    问题 在一个启用了IPVS模式kube-proxy的K8S集群中,运行着一个Docker Registry服务 ...
  • 念爷爷
      今天是爷爷的头七,十二月七日、阴历十月廿三中午,老人家与世长辞。   九月初,回家看望刚动完手术的爸爸,发

  • 6 杨梅坑

  • liuhuashan
    深圳人才公园的网红景点 —— 流花山

  • 1 2020年10月拈花湾

  • 内核缺陷触发的NodePort服务63秒延迟问题
    现象 我们有一个新创建的TKE 1.3.0集群,使用基于Galaxy + Flannel(VXLAN模式)的容 ...
  • Galaxy学习笔记
    简介 Galaxy是TKEStack的一个网络组件,支持为TKE集群提供Overlay/Underlay容器网 ...
TOPLINKS
  • Zitahli's blue 91 people like this
  • 梦中的婚礼 64 people like this
  • 汪静好 61 people like this
  • 那年我一岁 36 people like this
  • 为了爱 28 people like this
  • 小绿彩 26 people like this
  • 彩虹姐姐的笑脸 24 people like this
  • 杨梅坑 6 people like this
  • 亚龙湾之旅 1 people like this
  • 汪昌博 people like this
  • 2013年11月香山 10 people like this
  • 2013年7月秦皇岛 6 people like this
  • 2013年6月蓟县盘山 5 people like this
  • 2013年2月梅花山 2 people like this
  • 2013年淮阴自贡迎春灯会 3 people like this
  • 2012年镇江金山游 1 people like this
  • 2012年徽杭古道 9 people like this
  • 2011年清明节后扬州行 1 people like this
  • 2008年十一云龙公园 5 people like this
  • 2008年之秋忆 7 people like this
  • 老照片 13 people like this
  • 火一样的六月 16 people like this
  • 发黄的相片 3 people like this
  • Cesium学习笔记 90 people like this
  • IntelliJ IDEA知识集锦 59 people like this
  • 基于Kurento搭建WebRTC服务器 38 people like this
  • Bazel学习笔记 37 people like this
  • PhoneGap学习笔记 32 people like this
  • NaCl学习笔记 32 people like this
  • 使用Oracle Java Mission Control监控JVM运行状态 29 people like this
  • Ceph学习笔记 27 people like this
  • 基于Calico的CNI 27 people like this
Tag Cloud
ActiveMQ AspectJ CDT Ceph Chrome CNI Command Cordova Coroutine CXF Cygwin DNS Docker eBPF Eclipse ExtJS F7 FAQ Groovy Hibernate HTTP IntelliJ IO编程 IPVS JacksonJSON JMS JSON JVM K8S kernel LB libvirt Linux知识 Linux编程 LOG Maven MinGW Mock Monitoring Multimedia MVC MySQL netfs Netty Nginx NIO Node.js NoSQL Oracle PDT PHP Redis RPC Scheduler ServiceMesh SNMP Spring SSL svn Tomcat TSDB Ubuntu WebGL WebRTC WebService WebSocket wxWidgets XDebug XML XPath XRM ZooKeeper 亚龙湾 单元测试 学习笔记 实时处理 并发编程 彩姐 性能剖析 性能调优 文本处理 新特性 架构模式 系统编程 网络编程 视频监控 设计模式 远程调试 配置文件 齐塔莉
Recent Comments
  • qg on Istio中的透明代理问题
  • heao on 基于本地gRPC的Go插件系统
  • 黄豆豆 on Ginkgo学习笔记
  • cloud on OpenStack学习笔记
  • 5dragoncon on Cilium学习笔记
  • Archeb on 重温iptables
  • C/C++编程:WebSocketpp(Linux + Clion + boostAsio) – 源码巴士 on 基于C/C++的WebSocket库
  • jerbin on eBPF学习笔记
  • point on Istio中的透明代理问题
  • G on Istio中的透明代理问题
  • 绿色记忆:Go语言单元测试和仿冒 on Ginkgo学习笔记
  • point on Istio中的透明代理问题
  • 【Maven】maven插件开发实战 – IT汇 on Maven插件开发
  • chenlx on eBPF学习笔记
  • Alex on eBPF学习笔记
  • CFC4N on eBPF学习笔记
  • 李运田 on 念爷爷
  • yongman on 记录一次KeyDB缓慢的定位过程
  • Alex on Istio中的透明代理问题
  • will on Istio中的透明代理问题
  • will on Istio中的透明代理问题
  • haolipeng on 基于本地gRPC的Go插件系统
  • 吴杰 on 基于C/C++的WebSocket库
©2005-2025 Gmem.cc | Powered by WordPress | 京ICP备18007345号-2