0

I have an executable which is on a Server. Many users can login to this server, using SSH and execute the binary.

I would like to have an exclusive access to each user executing this binary. If possible, I would like to have a queue of users, which would be served one by one.

Is it possible to do this using bash script?

Suppose I call my binary as my.exec and the script as access.sh. I can guarantee that each user will access my.exec only through access.sh. So it will be easy to write a wrapper on top of this executable.

In addition the executable needs to be supplied variable arguments.

I have a partial solution here -

#!/bin/bash

# Locking
LOCK_FILE="/tmp/my.lock"

function create_lock_and_execute {
        echo "Waiting for Lock"
        while [ -f ${LOCK_FILE} ]
        do
            username=`ls -l ${LOCK_FILE} | cut -f 3 -d " "`
            echo $username is using the lock.
            sleep 1
        done


        (   
          # Wait for lock ${LOCK_FILE} (fd 200). 
          flock -x 200 

          echo "Lock Acquired..."

          # Execute Command
          echo "Executing Command : $COMMAND"
          ${COMMAND}

        ) 200>${LOCK_FILE}
}

function remove_lock {
    rm -f ${LOCK_FILE}
}

# Exit trap function
function exit_on_error {
    echo "Exiting on error..."
    remove_lock
    exit 1
}

# Exit on kill
function exit_on_kill {
    echo "Killed, exiting..."
    remove_lock
    exit 1
}

# Exit normaly
function exit_on_end {
    echo "Exiting..."
    remove_lock
    exit 0
}

trap exit_on_kill KILL
trap exit_on_error ERR
trap exit_on_end QUIT TERM EXIT INT

create_lock_and_execute

Thanks

Raj
  • 3,300
  • 8
  • 39
  • 67

1 Answers1

1

check How to prevent a script from running simultaneously?. for example

Else you can manually check for a file, if that file does not exist, create it and go ahead. Then after everything is done, delete the file. But this is not truly secure. There can be concurrent attempt and the check might fail

Update:

I have a link to share, I saw it sometime back, took a little time to dig up. But I have not checked it. Seems fine on quick look, but please test properly if you use this

http://gotmynick.github.io/articles/2012/2012-05-02-file_locks_queues_and_bash.html

Community
  • 1
  • 1
abasu
  • 2,454
  • 19
  • 22
  • I think this is a part of the answer. However, I don't understand how can I maintain a queue of requests. – Raj Apr 23 '13 at 16:30
  • I am not too sure if the solution you provided in the work for multi-user environment. – Raj Apr 25 '13 at 08:26