Создать init d linux

Creating your own linux custom init scripts

There are basically two standard types of linux system init.d scripts. They are the LSB and SysV init style init scripts.

Sysv init script writing method has traditionally been used to write init scripts in many linux distributions and is preferred as it gives more flexibility that earlier unix BSD style init script processes lacked. However, the more recent LSB (linux standard base) init.d script standard is widely used for its ability to reduce the challenges faced when migrating between different linux distributions and hence the difference between the scripting techniques is minimal.

Most Sysv init scripts are stored in the /etc/rc.d/init.d/ or /etc/init.d directory and are used to control how daemons start or stop up during system shutdown and startup.

SystemV-style initscripts and LSB header templates with detailed explained sections

#!/bin/sh # # # # chkconfig: # description: ### BEGIN INIT INFO # Provides: # Required-Start: # Required-Stop: # Should-Start: # Should-Stop: # Default-Start: # Default-Stop: # Short-Description: # Description: ### END INIT INFO
### BEGIN INIT INFO # Provides: OurDB # Required-Start: $local_fs $network $remote_fs # Required-Stop: $local_fs $network $remote_fs # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: start and stop OurDB # Description: OurDB is a very fast and reliable database # engine used for illustrating init scripts ### END INIT INFO

When creating a script for the first time to startup your application, the run-level process as sequenced in the /etc/inittab file will probably warn you about the script failing to meet all requirements, which is less of a risk given the script will still work as long as the syntaxes are correctly written. A critical example is the # chkconfig syntax.

##!/bin/bash # # chkconfig: 35 90 12 # description: Foo server # # Get function from functions library . /etc/init.d/functions # Start the service FOO start() < initlog -c "echo -n Starting FOO server: " /path/to/FOO & ### Create the lock file ### touch /var/lock/subsys/FOO success $"FOO server startup" echo > # Restart the service FOO stop() < initlog -c "echo -n Stopping FOO server: " killproc FOO ### Now, delete the lock file ### rm -f /var/lock/subsys/FOO echo > ### main logic ### case "$1" in start) start ;; stop) stop ;; status) status FOO ;; restart|reload|condrestart) stop start ;; *) echo $"Usage: $0 " exit 1 esac exit 0 echo "Usage: 

a wrong # chkconfig syntax error will make it hard for chkconfig to call the script when it is time for the scripts to enter its specified run-level.

# chkconfig: 2345 20 80 # description: Saves and restores system entropy pool for \ # higher quality random number generation.

It is always advisable not to manipulate the scripts manually but to let the to let chkconfig handle updating the /etc/init.d directory. A closer look at the chkonfig functions in a init.d script; the first line tells chkconfig what run-levels the service should be started in by default, as well as the start and stop priority levels. If the service should not, by default, be started in any run-levels, a should be used in place of the run-levels list.

The second line contains a description for the service, and may be extended across multiple lines with backslash continuation. The /etc/innitab file makes it easier for the system during startup to understand the applications to run at certain run-levels and execute them .

A default innittab file template structure

# # inittab This file describes how the INIT process should set up # the system in a certain run-level.# Default run level. The run levels are: # 0 - halt (Do NOT set initdefault to this) # 1 - Single user mode # 2 - Multiuser, without NFS # (The same as 3, if you do not have networking) # 3 - Full multiuser mode # 4 - unused # 5 - X11 # 6 - reboot (Do NOT set initdefault to this) # id:5:initdefault:

There are several tools available to relieve System administrators from directly updating the /etc/init.d directory which contains several other subdirectories directories that links it to the /etc/rc[x].d directory hierachy with numerous symbolic links contained in it.

In a Red-hat or cent OS systems the chkconfig tool or the ntsysv are mostly useful to accomplish the process of updating the /etc/init.d directory and you can therfore run the commands as root to enable the scripts automatically at boot.

chkconfig –add scriptname

chkconfig scriptname on

Running chkconfig --list scriptname should help you know whether the script will correctly be executed when entering/exiting the relevant runlevels.

on Debian-based distributions you can do this by running

update-rc.d scriptname defaults

A deep understanding of the shell functions provided by the init.d scripts is needed while filling them in the init.d bash scripts as failure to do so may possibly deliver unpredictable results while your system attempts to execute certain applications or daemons at run-levels.

Related articles
  • Steps for booting Slackware to GUI, and some details on runlevels (slackerboyabhi.wordpress.com)
  • Linux Rebooting Refresh (ostatic.com)
  • How Does Linux Work ? ( 12 steps) (osamajaber.wordpress.com)
  • Initscripts (wiki.archlinux.org)
  • init 1.0 (freecode.com)
  • jboss (redhatlinux4u.wordpress.com)

Источник

How to create init.d startup script

I just want to run a very simple command on startup. How can I do that? I've searched google and it has very complicated examples, but what I need is just run this script on startup. How can I do that? Script ./init.d/opscenter-agent start

3 Answers 3

If you want to do this as system startup (as opposed to when you log in to your computer), put the commands you want to run in /etc/rc.local .

The OP specifically asked for an init.d script, which this is really not. It's a related approach, mostly by virtue of it's being the way we did things 30 odd years ago, and more or less never do now thanks to newer approaches like init.d. (which is in turn being deprecated in favour of systemd's /etc/init).

If the script does not need to be run by root, you can do this:

1) Open "Startup Applications Preferences" ( Alt + F2 and paste gnome-session-properties and hit Enter ),

2) Press "Add" and select your script:

enter image description here

enter image description here

If you are not using a graphical environment, you can put the commands just before the line exit 0 in this file: /etc/rc.local . (To edit it just paste at terminal sudo nano /etc/rc.local .

The /etc/rc.local approach will 'run a very simple command at startup', but it is not an init.d script approach, and is in various ways inferior. (That may not matter, depending on your purpose).

Unlike init.d scripts, rc.local comands don't offer a standard interface to starting and stopping a process, and they don't offer much ability to influence when in the startup process they are run. You can see in the /etc/init.d/rc.local script that this is run after everything else ( Required-Start: $all ).

If an init.d script really is what you want, then usually just grabbing an existing script, copying it and editing it works fine, though some of the existing scripts have more complexity than you want. Since that's how most init.d scripts start, ubuntu provides /etc/init.d/skeleton for this purpose.

  • /etc/init.d/motd is a minimal example that runs something at startup, but with the Required-Start parameter setting when it should happen.
  • /etc/init.d/cron is a simple starting point for a daemon process (give or take the parse_environment function, which you probably don't need).

Источник

Пишем Init скрипт

Инициализация — важнейшая процедура, лежащая в основе любой операционной системы на основе Unix/Linux для управления работой каждого скрипта и службы.

Я описывал в своих статьях процесс создания скриптов для systemD/Upstart и сейчас я хотел бы написать о написании init скриптов. Тема не новая и используется давно, но я большую часть своих тем беру именно из черновиков, которые накопились за года 3-4. У меня не хватает времени на все публикации + наполнять контент максимально (по крайней мере, сразу) и по этому, имеет что имеем. Но не смотря на это, у меня уже довольно много читателей — и это хорошо, это радует!

По сути, инициализация следует за этим процессом:

  • Загрузка сервера.
  • Запуск init процесса (обычно как PID 1).
  • Запуск предопределенного набора задач для запуска активируется последовательно.

Инициализация отвечает за то, чтобы сервер мог загрузиться и отключиться. В некоторых Unix/Linux дистрибутивах используется стандартный процесс инициализации init/systemD/Upstart.

Пишем Upstart скрипт

И так, хотелось бы рассказать как можно запускать томкат. Но для начала, нужно узнать какой механизм инициализации используется:

Т.к речь идет о sysv init/Upstart, то и продолжим тему.

PS: Вот еще полезное чтиво:

INIT скрипт может иметь следующие состояния:

  • start — Служит командой для запуска службы.
  • stop — Выполняет остановку службы.
  • restart — Перезапуст службы, а по факту — остановка и затем запуск сервиса.
  • reload — Перезагрузка службы, т.е команда для перечитывания конфигурации без перезапуска или остановки службы.
  • force-reload — Перезагрузка конфигурации (перечитать конфиг), если служба поддерживает это. В противном случае — выполнит перезапуск службы.
  • status — Покажет состояние службы.

Вот скилет скрипта для использования:

#!/bin/bash -x # # Source function library. . /etc/rc.d/init.d/functions case "$1" in start) echo -n "Starting services: " touch /var/lock/subsys/ ;; stop) echo -n "Shutting down services: " rm -f /var/lock/subsys/ ;; status) ;; restart) ;; reload) ;; probe) ;; *) echo "Usage: 

Данный каркас можно юзать для любых целей.

Примеры Init скрипта

Приведу наглядный пример запуска томката.

Запуск TOMCAT с init

Создадим init скрипт для запуска:

#!/bin/bash -x # # Provides: tomcat9 # Required-Start: $local_fs $remote_fs $network # Required-Stop: $local_fs $remote_fs $network # Should-Start: $named # Should-Stop: $named # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Start Tomcat. # Description: Start the Tomcat servlet engine. ### END INIT INFO export CATALINA_HOME=/usr/local/tomcat9 export JAVA_HOME=/usr/local/jdk1.8.0_131 export PATH=$JAVA_HOME/bin:$PATH service_name="tomcat9" start() < echo "Starting Tomcat 9. " /bin/su -s /bin/bash tomcat -c $CATALINA_HOME/bin/startup.sh >stop() < echo "Stopping Tomcat 9. " /bin/su -s /bin/bash tomcat -c $CATALINA_HOME/bin/shutdown.sh >status() < if (( $(ps -ef | grep -v grep | grep $service_name | wc -l) >0 )); then echo "$service_name is running. " else echo "$service_name is down. " fi > case $1 in start|stop|status) $1;; restart) stop; start;; *) echo "Usage : $0 "; exit 1;; esac exit 0

Даем права на запуск (на исполнение):

# chmod 755 /etc/init.d/tomcat9

Открываем браузер и смотрим что вышло!

#!/bin/bash -x DAEMON_PATH="/home/wes/Development/projects/myapp" DAEMON=myapp DAEMONOPTS="-my opts" NAME=myapp DESC="My daemon description" PIDFILE=/var/run/$NAME.pid SCRIPTNAME=/etc/init.d/$NAME case "$1" in start) printf "%-50s" "Starting $NAME. " cd $DAEMON_PATH PID=`$DAEMON $DAEMONOPTS > /dev/null 2>&1 & echo $!` #echo "Saving PID" $PID " to " $PIDFILE if [ -z $PID ]; then printf "%s\n" "Fail" else echo $PID > $PIDFILE printf "%s\n" "Ok" fi ;; status) printf "%-50s" "Checking $NAME. " if [ -f $PIDFILE ]; then PID=`cat $PIDFILE` if [ -z "`ps axf | grep $ | grep -v grep`" ]; then printf "%s\n" "Process dead but pidfile exists" else echo "Running" fi else printf "%s\n" "Service not running" fi ;; stop) printf "%-50s" "Stopping $NAME" PID=`cat $PIDFILE` cd $DAEMON_PATH if [ -f $PIDFILE ]; then kill -HUP $PID printf "%s\n" "Ok" rm -f $PIDFILE else printf "%s\n" "pidfile not found" fi ;; restart) $0 stop $0 start ;; *) echo "Usage: $0 " exit 1 esac

Подойдет к большинству скриптов, а для остальных — можно отредактировать немного.

И, вот еще полезный довольно вариант:

#!/bin/sh ### BEGIN INIT INFO # Provides: # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Start daemon at boot time # Description: Enable service provided by daemon. ### END INIT INFO dir="" cmd="" user="" name=`basename $0` pid_file="/var/run/$name.pid" stdout_log="/var/log/$name.log" stderr_log="/var/log/$name.err" get_pid() < cat "$pid_file" >is_running() < [ -f "$pid_file" ] && ps -p `get_pid` >/dev/null 2>&1 > case "$1" in start) if is_running; then echo "Already started" else echo "Starting $name" cd "$dir" if [ -z "$user" ]; then sudo $cmd >> "$stdout_log" 2>> "$stderr_log" & else sudo -u "$user" $cmd >> "$stdout_log" 2>> "$stderr_log" & fi echo $! > "$pid_file" if ! is_running; then echo "Unable to start, see $stdout_log and $stderr_log" exit 1 fi fi ;; stop) if is_running; then echo -n "Stopping $name.." kill `get_pid` for i in 1 2 3 4 5 6 7 8 9 10 # for i in `seq 10` do if ! is_running; then break fi echo -n "." sleep 1 done echo if is_running; then echo "Not stopped; may still be shutting down or shutdown may have failed" exit 1 else echo "Stopped" if [ -f "$pid_file" ]; then rm "$pid_file" fi fi else echo "Not running" fi ;; restart) $0 stop if is_running; then echo "Unable to stop, will not attempt to start" exit 1 fi $0 start ;; status) if is_running; then echo "Running" else echo "Stopped" exit 1 fi ;; *) echo "Usage: $0 " exit 1 ;; esac exit 0

Вот и все, статья «Пишем Init скрипт» завершена.

Источник

Читайте также:  Maemo 5 on linux
Оцените статью
Adblock
detector