linuxbashsocketsshellxinetd

Running shell script with xinetd in single instance mode


I would like to give a user some feedback when he is trying to execute a remote script that is started by xinetd and runs as single instance.

Via an UDP or TCP socket, the user sends some text to the port where xinetd is listening. If the script is not already in use, it is executed, but if not I would like to give the user some feedback like "Sorry, this script is already in use. Try again later." How could this be done? Thanks for any help.


Solution

  • On Linux you can use the flock utility from util-linux:

    if ! ( flock -n 42 || exit 1
    
        # Things to do in the single instance
        echo "Processing..."
        sleep 60 
        echo "Done" 
    
        exit 0
     ) 42> /var/tmp/mylockfile  # any unique filename
    then 
        # Things to do when the script is in use
        echo "Sorry, the service is in use."
    fi
    

    Just make sure that the subshell in () ends with success (like with exit 0 here), otherwise the then-clause kicks in after your process is finished.