Location of the script
/etc/init.d is the well known location, but actually /etc/rc.d/init.d is the real original location. Since /etc/init.d is a hard link to /etc/rc.d/init.d, it makes no difference.Header of the script
It needs at least 3 lines. The shell script interpreter (/bin/sh, /bin/bash .. etc), the chkconfig header and script description#!/bin/sh # chkconfig: 345 56 10 # description: Startup/shutdown script for the Common UNIX
Body of the script
Obviously, it need to accept parameter “start”, which /etc/rc3.d/S* will call on OS startup and accept parameter “stop”, which /etc/rc0.d/K* script will call on OS shutdown.The lockfile is often overlooked, it is used to check the existence of the daemon on OS shutdown, otherwise the stop action won’t be called. If you found an issue that a script started on OS startup but never stop properly on shutdown, you need to create lockfile. note: lockfile is not pidfile which contains PID of the process, lockfile is usually a blank file.
lockfile=/var/lock/subsys/$(basename $0) case $1 in start) start [ $? = 0 ] && touch $lockfile ;; stop) stop [ $? = 0 ] && rf –f $lockfile
Others
It is recommended to import functions in /etc/rc.d/init.d/functions to use ‘daemon’ to startup your application or killproc to shutdown your application instead of reinventing the wheel.LSB headers
You may see something like this in an init script.# Provides: boot_facility_1 [ boot_facility_2 ...] # Required-Start: boot_facility_1 [ boot_facility_2 ...] # Required-Stop: boot_facility_1 [ boot_facility_2 ...] # Should-Start: boot_facility_1 [ boot_facility_2 ...] # Should-Stop: boot_facility_1 [ boot_facility_2 ...] # Default-Start: run_level_1 [ run_level_2 ...] # Default-Stop: run_level_1 [ run_level_2 ...] # Short-Description: short_description # Description: multiline_descriptionThey are LSB(Linux Standard Base) headers, they are supported by default in Debian and SUSE Linux.
Red Hat Linux supports this by additional package “redhat-lsb” and it is not installed by default, Be warned,50+ dependences need to installed as well.
Reference
http://refspecs.linuxfoundation.org/LSB_2.1.0/LSB-generic/LSB-generic/initscrcomconv.htmlhttps://fedoraproject.org/wiki/Packaging:SysVInitScript?rd=Packaging/SysVInitScript