Linux service start on startup

How to start a service automatically, when Ubuntu starts?

I am using Ubuntu 12.04 and want to have a service starting, when the system is booted normally. As ‘service’ I understand some code, for example cd my_directory; my_command -host 0.0.0.0 -port 1234 -arg x that just should be running as if it has been started on the command line. There are services to be started as normal user, but also services to be started as root (in fact, it is not required the services to be run on user level). I also require to configure the behavior when a ‘service’ stops. I want them to be restarted in my case, with the same argument, in a specified directory. All of the services should be started automatically when the system is started normally, i.e. if the power switch is pressed. No other action should be required. There are some documents spread on the internet, but they all confuse me. They talk about init , init.d , rc.d , but I never saw a simple-to-follow step-by-step instruction to easily as a service using e.g. upstart. If this is easy, I would appreciate if those steps are given here.

2 Answers 2

To create a job to be started automatically when Ubuntu starts, use the example given here. As written example, suppose to create the following file /etc/init/testservice.conf with sudo:

# testservice - test service job file description "my service description" author "Me " # Stanzas # # Stanzas control when and how a process is started and stopped # See a list of stanzas here: http://upstart.ubuntu.com/wiki/Stanzas # When to start the service start on runlevel [2345] # When to stop the service stop on runlevel [016] # Automatically restart process if crashed respawn # Essentially lets upstart know the process will detach itself to the background # This option does not seem to be of great importance, so it does not need to be set. #expect fork # Specify working directory chdir /home/user/testcode # Specify the process/command to start, e.g. exec python mycommand.py arg1 arg2 

To ‘manually’ start or stop the process use

sudo start testservice sudo stop testservice 

Ok, Alex, the point is that all the userspace processes in Linux are started with init process, whose pid is 1. For instance, run pstree to see the tree of your processes, whose root is init.. There are several versions of init process implementation nowadays, most notable are

  • sysVinit (classical init, still used by some distributions, including older Debian)
  • Upstart init, used by older Ubuntu and some RHEL (Red Hat) and older Fedora versions
  • systemd init, used by modern Fedora, Ubuntu, Debian, RHEL, SUSE versions
Читайте также:  Линукс что выбрать для сервера

Traditionally, Unix’es used init implementation called sysVinit init, called by the name of https://ru.wikipedia.org/wiki/UNIX_System_V version of Unix. It is very influential and other inits are backward compatible to it.

Basically, sysVinit first reads /etc/inittab file, decides, which runlevel to run and tells /etc/init.d/rc script to execute so-called init scripts. E.g. when it normally boots to a multi-user runlevel, which is usually runlevel 2 on Ubuntu, /etc/init.d/rc starts executing scripts in /etc/rc2.d . Files there are only symbolic links to scripts, while the scripts themselves are stored in /etc/init.d directory. The naming of those symlinks in /etc/rc*.d directories is as follows. Say, we’ve got the following scripts in /etc/rc2.d :

$ls /etc/rc2.d S16rsyslog S17apache2 K02network-manager 

It means, that upon switching to runlevel 2 init process first kills network-manager processes, cause its script name starts with K — K02network-manager and then starts processes, whose names start with S . The two digits after S or K is the number from 00 to 99, which determines the order, the processes are started in. E.g. rsyslog is started before apache2 , because 16 is less than 17 (that makes sense, cause you want apache to rely upon rsyslog’s logging capacities, thus rsyslog should be started first). The scripts are casual shell scripts, executed by #!/bin/sh .

So, basically to start a program upon startup in sysVinit style, write your own script (copy-pasting it from any example, you’ve got in /etc/init.d ), put it to /etc/init.d and create a symlink to it under a reasonable name, e.g. S99mytrojan in /etc/rc2.d . Here’s an explanation of typical sysVinit scripts in /etc/init.d http://docs.oracle.com/cd/E19683-01/806-4073/6jd67r96g/index.html

Now, Ubuntu guys decided that they want additional functionality from init. They wanted a fast booting OS, so they wanted their scripts to be executed in parallel; they wanted dead processes to be automatically restarted; they wanted the processes to invoke each other in an explicit manner by events (so that apache is run by «syslog started» event, and syslog is run by «file systems mounted» event etc., so we have events instead of some numbers 00-99). Thus, they’ve made Upstart and here is how it works. Upstart initscripts are put in /etc/init directory (don’t confuse with /etc/init.d ). Upstart usually runs /etc/init.d/rc too, so it’s gonna execute your sysVinit scripts normally. But if you want your script to be respawned upon exit — Upstart events are for you.

Although I can’t check that my script is working, I suppose, that for your aims, you should write the following /etc/init/mytrojan.conf script:

start on runlevel [02] respawn exec mytrojan --argument X 

But if you need dependencies, at least filesystems and network, may be it makes sense to replace start on runlevel [02] with something like:

start on (local-filesystems and net-device-up IFACE!=lo) 

WARNING: I didn’t check the correctness of this, cause I can’t. Especially, I’m not quite sure about how to start script after your network connection is up and running (I used this version). Try googling for «upstart on network up».

Читайте также:  Iso image for linux

Источник

How to start program at Linux boot automatically

Linux startup consists of several stages, during which you can configure a program to start automatically. This can be a single command, a sequence of commands, or an executable shell script. However, startup procedures may vary between different Linux distributions and versions.

Modern Linux systems boot into systemd, while older Linux versions utilize System V init. Regardless, both systems will execute cron and rc.local before loading the desktop environment, such as GNOME or KDE. In contrast, server-based Linux distributions do not load a desktop environment and instead provide a login prompt at the console. After logging in, the default shell like Bash runs.

Methods to automatically run program on Linux startup:

Running a program automatically on Linux startup via systemd

systemd is the standard system and service manager in modern Linux, responsible for executing and managing programs during startup, among other tasks. Compatible programs will include service unit files used by systemd to manage the program’s execution.

To configure systemd to run a program automatically during Linux startup, follow these steps:

$ sudo systemctl list-unit-files --type=service [sudo] password for user: UNIT FILE STATE accounts-daemon.service enabled apparmor.service enabled apport-autoreport.service static apport-forward@.service static apport.service generated apt-daily-upgrade.service static apt-daily.service static atd.service enabled autovt@.service enabled blk-availability.service enabled bootlogd.service masked bootlogs.service masked bootmisc.service masked checkfs.service masked checkroot-bootclean.service masked checkroot.service masked cloud-config.service enabled cloud-final.service enabled cloud-init-local.service enabled cloud-init.service enabled console-getty.service disabled ##### snipped #####

You’ll have to create your own service unit if it’s a custom program or if your program doesn’t come with one during installation
Related: Creating and modifying systemd unit files

$ sudo systemctl is-enabled mysql disabled
$ sudo systemctl enable mysql Synchronizing state of mysql.service with SysV service script with /lib/systemd/systemd-sysv-install. Executing: /lib/systemd/systemd-sysv-install enable mysql Created symlink /etc/systemd/system/multi-user.target.wants/mysql.service → /lib/systemd/system/mysql.service.
$ sudo systemctl is-enabled mysql enabled

Running a program automatically on Linux startup via cron

cron is a daemon used to execute scheduled commands stored in the cron job table (crontab), which is unique for each user in the system. It starts during system boot, either via systemd or System V init, and you can schedule your program to run during system boot by following these steps:

You’re required to select an editor for the crontab if this is the first time the user uses the command.

$ crontab -e no crontab for user - using an empty one Select an editor. To change later, run 'select-editor'. 1. /bin/nano 

A crontab will be created for the user running the command and will be executed using the privileges of the user. If you need your program to run as the root user, run crontab -e as the root user itself.

# m h dom mon dow command @reboot
@reboot /sbin/ip addr | grep inet\ | tail -n1 | awk '< print $2 >' > /etc/issue && echo "" >> /etc/issue
$ crontab -e crontab: installing new crontab $
$ crontab -l # m h dom mon dow command @reboot /sbin/ip addr | grep inet\ | tail -n1 | awk '< print $2 >' > /etc/issue && echo "" >> /etc/issue

Running a program automatically on Linux startup via rc.local

rc.local is a legacy script from the System V init system, executed before displaying a login screen for the desktop environment or terminal login prompt. It is typically a Bash shell script capable of running any commands.

To configure your rc.local script, follow these steps:

As the root user, open or create the /etc/rc.local file using your preferred editor if it doesn't exist.

#!/bin/bash /sbin/ip addr | grep inet\ | tail -n1 | awk '< print $2 >' > /etc/issue echo "" >> /etc/issue exit 0

Running a program automatically on GNOME startup

GNOME is the default desktop environment for Linux distributions like Ubuntu and Red Hat. You can configure GNOME to run programs upon user login by following the instructions in the linked article:

Running a program automatically on KDE startup

KDE is another popular Linux desktop environment and the default for Kubuntu and openSUSE. It can also be configured to run programs when a user logs in, as detailed in the related article:

Running a program automatically on new Bash session

A new shell program will be spawned when you start your terminal session. Bash is the default shell for most Linux distributions, and when started, it will look for the following files in the particular starting a terminal session, a new shell program will be spawned. Bash is the default shell for most Linux distributions and, when initiated, looks for and executes the following files in order:

/etc/profile ~/.bash_profile ~/.bash_login ~/.profile

These files contain commands and logic for setting up environment variables and running required programs in the Bash language. They are also typically configured to execute other files, such as /etc/bashrc, /etc/bash.bashrc, and ~/.bashrc.

You can edit any of these files to run your program when a Bash session is started. Below is a part of a typical ~/.bashrc file:

PS1='$\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] \$ ' PATH=/home/user/bin:$PATH export EDITOR=/usr/bin/vim alias ll="ls -l"

Author: Mohd Shakir Zakaria
Mohd Shakir Zakaria, a proficient cloud architect, is deeply rooted in development, entrepreneurship, and open-source advocacy. As the founder of Simplified Guide, he combines these passions to help others navigate the intricate world of computing. His expertise simplifies complex tech concepts, making them accessible to everyone. Discuss the article:

Comment anonymously. Login not required.

Источник

Оцените статью
Adblock
detector