Simple Steps to Create a Service in Linux

Harsh S.
By
Harsh S.
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale...
6 Min Read

Greetings Readers! Welcome to an interesting article on Linux daemon/Linux service.

Let’s Begin to Create a Linux Service

The idea behind writing this article is not only to tell you the steps for writing a service. Instead, we thought to present you with a special script that can run on any Linux platform or any Linux distribution.

Linux service using shell script.
Linux service using a shell script.

What is a Service in Linux?

A Linux service is a process that constantly runs in the background. You can though control it using a shell script which can alter the state of the service on demand. There are usually four states defined for a service i.e. start, stop, reload, and restart. And are set from the terminal either by <root> or <sudo> users.

Note: During this article, we’ll be using the words ‘service’ and ‘daemon’ at different times, but both mean the same.

Simple Steps to Create the Service

You only need to follow a few steps to create the Linux service. We have streamlined them for you here.

Create Linux Daemon in Shell Script

Prepare the Service Template

Let’s assume you have an application to monitor the no of users logged in and logged out. And you need this app to run uninterrupted in the background. The best approach to achieve this is by creating a Linux service. For this, go to the correct directory path and create the script either by root or <sudo> privileged user.

cd /etc/init.d/
vim linuxsvc

Basic Service Template

Where <linuxsvc> is the name of your Linux service. Now let’s look at its basic structure.

Write the service for Linux
#!/bin/sh

start() {
    echo "Starting service..."
    # Add start logic here
}

stop() {
    echo "Stopping service..."
    # Add stop logic here
}

status() {
    echo "Checking service status..."
    # Add status logic here
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status
        ;;
    force-reload|restart)
        stop
        start
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|force-reload|status}"
        exit 1
        ;;
esac

Full Linux Service Code

You now need to copy and paste the below code snippet into your service shell script i.e. </etc/init.d/linuxsvc>. We are assuming that the user’s monitoring app is available at </usr/local/bin/linuxsvc>. Also, we choose the monitoring app name similar to <linuxsvc>. In case you want a different name, change it accordingly.

Working Code

Review the Linux Daemon Code
#!/bin/sh
### Root user check
if [ "$(id -u)" -ne 0 ]; then
    echo "$0 needs to be run as root or with sudo."
    exit 1
fi

# Daemon files
USER_MONITOR_FILE="/usr/local/bin/linuxsvc"

# Check if the user application exists
if [ ! -f "$USER_MONITOR_FILE" ]; then
    echo "Error: Daemon file $USER_MONITOR_FILE not found!"
    exit 1
fi

# Detect OS type
if [ -e /etc/rc.d/init.d/functions ]; then
    USER_OS="RedHat"
elif [ -e /etc/rc.status ]; then
    USER_OS="SUSE"
elif [ -e /etc/debian_version ]; then
    USER_OS="Debian"
elif [ -e /lib/lsb/init-functions ]; then
    USER_OS="LSB"
else
    USER_OS="Unknown"
fi

# Load OS-specific functions
case $USER_OS in
    SUSE)
        . /etc/rc.status
        rc_reset
        ;;
    LSB)
        . /lib/lsb/init-functions
        ;;
    RedHat)
        . /etc/rc.d/init.d/functions
        ;;
esac

linux_start_daemon() {
    echo -n "Starting $2 daemon... "

    case $USER_OS in
        SUSE)
            startproc $1 $3
            rc_status -v
            ;;
        Debian)
            start-stop-daemon --start --quiet --exec $1 -- $3
            echo "Done."
            ;;
        LSB)
            start_daemon $1 $3
            echo "Done."
            ;;
        RedHat)
            daemon $1 $3
            echo
            ;;
        *)
            if ! pgrep -f "$1" >/dev/null 2>&1; then
                $1 $3
            fi
            echo "Done."
            ;;
    esac
}

linux_stop_daemon() {
    echo -n "Stopping $2 daemon... "

    case $USER_OS in
        SUSE)
            killproc $1
            rc_status -v
            ;;
        Debian)
            start-stop-daemon --stop --quiet --retry 8 --exec $1
            echo "Done."
            ;;
        LSB | RedHat)
            killproc $1
            echo "Done."
            ;;
        *)
            if pgrep -f "$1" >/dev/null 2>&1; then
                pkill -f "$1" >/dev/null 2>&1
                for _ in {1..8}; do
                    if ! pgrep -f "$1" >/dev/null 2>&1; then break; fi
                    sleep 1
                done
                if pgrep -f "$1" >/dev/null 2>&1; then
                    pkill -9 -f "$1" >/dev/null 2>&1
                    sleep 1
                fi
            fi
            echo "Done."
            ;;
    esac
}

linux_status_daemon() {
    if pgrep -f "$1" > /dev/null 2>&1; then
        echo "$2 is running."
    else
        echo "$2 is NOT running!"
    fi
}

start() {
    linux_start_daemon "$USER_MONITOR_FILE" "LINUXSVC" ""
}

stop() {
    linux_stop_daemon "$USER_MONITOR_FILE" "LINUXSVC"
}

status() {
    linux_status_daemon "$USER_MONITOR_FILE" "LINUXSVC"
}

case "$1" in
    start) start ;;
    stop) stop ;;
    status) status ;;
    force-reload | restart)
        stop
        start
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|force-reload|status}"
        exit 1
        ;;
esac

# OS-specific exit handling
case $USER_OS in
    SUSE) rc_exit ;;
    RedHat) exit $? ;;
    *) exit 0 ;;
esac

Start Linux Service

Before you start using the service, please change its permissions as mentioned below.

chmod +x /etc/init.d/linuxsvc -v

Once you are done, then launch your Linux service for the first time.

service linuxsvc start

Key Takeaways from this Linux Service

Like this Linux service?
Did you like our Linux service?

Thanks for reading this article. We hope this ultimate Linux script will be useful for you. We host some of the best Shell scripting quizzes, see if you like to play around with them.

Lastly, our site needs your support to remain free. Share this post on social media and subscribe to our YouTube channel for more knowledgeful tutorials.

Enjoy Coding!

Share This Article
Subscribe
Notify of
guest

0 Comments
Newest
Oldest
Inline Feedbacks
View all comments