Skip to content
Advertisement

Background process in linux

I have developed a Java socket server connection which is working fine.

When started from a terminal, it starts from listening from client. But when I close the terminal it stops listening.

I need to continue even though the terminal closed by user from where jar file was started.

How can I run Java server socket application in Linux as background process?

Advertisement

Answer

There are several ways you can achieve such a thing:

  1. nohup java -server myApplication.jar > /log.txt – this is pretty straight forward. It will just put the application in the background. This will work but it’s just not a very good way to do so.
  2. Use a shell wrapper and the above OR daemon app. This approach is used by many open source projects and it’s quite good for most of the scenarios. Additionally it can be included in init.d and required run level with regular start, stop and status commands. I can provide an example if needed.
  3. Build your own daemon server using either Java Service Wrapper or Apache Jakarta Commons Daemon. Again – both are extremely popular, well tested and reliable. And available for both Linux and Windows! The one from Apache Commons is used by Tomcat server! Additionally there is Akuma.

Personally I would go with solution 2 or 3 if you need to use this server in the future and/or distribute it to clients, end users, etc. nohup is good if you need to run something and have no time to develop more complex solution for the problem.

Ad 2:

The best scripts, used by many projects, can be found here.

For Debian/Ubuntu one can use a very simple script based on start-stop-daemon. If in doubt there is /etc/init.d/skeleton one can modify.

#!/bin/sh

DESC="Description"
NAME=YOUR_NAME
PIDFILE=/var/run/$NAME.pid
RUN_AS=USER_TO_RUN
COMMAND=/usr/bin/java -- -jar YOUR_JAR

d_start() {
    start-stop-daemon --start --quiet --background --make-pidfile --pidfile $PIDFILE --chuid $RUN_AS --exec $COMMAND
}

d_stop() {
    start-stop-daemon --stop --quiet --pidfile $PIDFILE
    if [ -e $PIDFILE ]
        then rm $PIDFILE
    fi
}

case $1 in
    start)
    echo -n "Starting $DESC: $NAME"
    d_start
    echo "."
    ;;
    stop)
    echo -n "Stopping $DESC: $NAME"
    d_stop
    echo "."
    ;;
    restart)
    echo -n "Restarting $DESC: $NAME"
    d_stop
    sleep 1
    d_start
    echo "."
    ;;
    *)
    echo "usage: $NAME {start|stop|restart}"
    exit 1
    ;;
esac

exit 0
Advertisement