简体   繁体   中英

Terminate bash script if process already running

I'm using a startup script to start our Minecraft server via webmin on CentOS. It backs up a few files before starting the server itself. Recently we messed up our data by accidentally executing the script twice in a row, which resulted two instances of the Minecraft server being run and everything went haywire with data files and such.

To prevent this from happening, I want the script to terminate if it detects that the process is running. I've searched around for similar problems, and things like lock files are suggested, but I don't have the opportunity to remove those since the startup script only sets up a screen for the Minecraft server process and stopping the server is usually done by terminating the screen or stopping the server through ingame commands.

The server process is started using this command:

screen -dmS minecraft java -Xincgc -Xmx2G -jar server.jar

How can I make the startup script detect if this process is already running, and then terminate itself?

Use this script:

#!/bin/bash
LOCKDIR="/path/to/lockdir"

if [ ! mkdir "$LOCKDIR" ]; then
    echo >&2 "Server is already running"
    exit 1
fi

# Here: when exiting, or receiving any of the mentioned signals, remove the lock file      
trap "rmdir \"$LOCKDIR\"" exit INT HUP TERM QUIT
 
# It would be tempting to exec instead, but DON'T DO IT: otherwise the trap is forgotten
minecraft java -Xincgc -Xmx2G -jar server.jar

exit $?

and launch it within your screen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM