1.5.3 服务启动脚本

上节在介绍Linux运行级时,谈到在Linux启动过程中会使用K或S开头的脚本关闭或启动相关服务,那么这是怎么做到的呢?本节将通过一个脚本帮助大家理解。当然因为这里还没有讲到Shell编程的内容,所以只做非常简单的讲解。


  1. #!binbash

  2. #

  3. 一个bash

  4. 脚本开始的标记,必须是用“#!binbash

  5. ”开头,含义是提示系统在运行该脚本时使用

  6. binbash

  7. 作为执行该文件的解释器

  8. # etcrc.d/init.d/atd

  9. #

  10. 说明自己的绝对路径

  11. # Starts the at daemon

  12. #

  13. # chkconfig: 345 95 5

  14. #345

  15. 是说在运行级是345

  16. 的时候,默认开启atd

  17. ,也就是Start

  18. #95

  19. 是说明当默认设置为on

  20. 的时候,运行优先级定为95

  21. #5

  22. 是说明当默认设置为off

  23. 的时候,停止优先级定为5

  24. # description: Runs commands scheduled by the at command at the time

  25. # specified when at was run, and runs batch commands when the load

  26. # average is low enough.

  27. # processname: atd

  28. # Source function library.

  29. . etcinit.d/functions

  30. #

  31. 使用“.

  32. ”命令包含文件,可以使用etcinit.d/functions

  33. 中定义的函数

  34. # pull in sysconfig settings

  35. [ -f etcsysconfig/atd ] && . etcsysconfig/atd

  36. test -x usrsbin/atd || exit 0

  37. RETVAL=0

  38. #

  39. # See how we were called.

  40. #

  41. prog="atd"

  42. start() {

  43. # Check if atd is already running

  44. if [ ! -f varlock/subsys/atd ]; then

  45. echo -n $"Starting $prog: "

  46. daemon usrsbin/atd $OPTS && success || failure

  47. RETVAL=$?

  48. [ $RETVAL -eq 0 ] && touch varlock/subsys/atd

  49. echo

  50. fi

  51. return $RETVAL

  52. }

  53. #

  54. 定义start

  55. 函数

  56. stop() {

  57. echo -n $"Stopping $prog: "

  58. killproc usrsbin/atd

  59. RETVAL=$?

  60. [ $RETVAL -eq 0 ] && rm -f varlock/subsys/atd

  61. echo

  62. return $RETVAL

  63. }

  64. #

  65. 定义stop

  66. 函数

  67. restart() {

  68. stop

  69. start

  70. }

  71. #

  72. 定义restart

  73. 函数,实际调用时,先执行stop

  74. 函数后执行start

  75. 函数

  76. reload() {

  77. restart

  78. }

  79. #

  80. 定义reload

  81. 函数,实际调用时,就是执行restart

  82. 函数

  83. status_at() {

  84. status usrsbin/atd

  85. }

  86. #

  87. 定义status_at

  88. 函数,实际调用时,是调用etcinit.d/functions

  89. 中定义的函数status

  90. 参数为usrsbin/atd

  91. ,也就是查询atd

  92. 的运行状态

  93. case "$1" in

  94. start)

  95. start

  96. ;;

  97. stop)

  98. stop

  99. ;;

  100. reload|restart)

  101. restart

  102. ;;

  103. condrestart)

  104. if [ -f varlock/subsys/atd ]; then

  105. restart

  106. fi

  107. ;;

  108. status)

  109. status_at

  110. ;;

  111. *)

  112. echo $"Usage: $0 {start|stop|restart|condrestart|status}"

  113. exit 1

  114. esac

  115. exit $?

  116. exit $RETVAL


上面的脚本实际上是etcinit.d/atd中的内容,我在脚本中做了一些注释来简单讲解脚本的处理过程。当atd设置为启动时,将会在对应的etcrcX.d(X代表0~6)目录下显示:S95atd->../init.d/atd,系统根据第一个字母S判定atd需要启动,然后会调用命令etcinit.d/atd start;当atd设置为关闭时,将会在对应的etcrcX.d目录下显示:K05atd->../init.d/atd,系统根据第一个字母K判定atd需要关闭,然后调用命令etcinit.d/atd stop,这样就实现了对atd的启停控制,其他服务也是同样的原理。