How to Lock the Script?


 
Thread Tools Search this Thread
Top Forums UNIX for Dummies Questions & Answers How to Lock the Script?
# 1  
Old 11-25-2013
How to Lock the Script?

Hi All,

Seeking for your assistance on how to lock the script if it's running? meaning anybody can't run my script while it's running.

Please advise,

Thanks,
# 2  
Old 11-25-2013
Hello,

You can add the following in your script and try.


Code:
value_script_run=`ps -ef | grep -v grep | grep test.ksh`
if [[ -z $value_script_run ]]
then
 
all your code........
 
else
echo "script is running currently."
fi


This may help you.



Thanks,
R. Singh
# 3  
Old 11-25-2013
To respond to the suggestions from RavinderSingh13

The problem with looking for a process of the right name is that someone could be editing a file of the same/similar name, or using more to browse the script. They will all get detected as an in-use condition.

It would be neater written as:-
Code:
if [ `ps -ef | grep -c [t]est.ksh` -ne 1 ]
then

... although I'm probably breaking all sorts of rules about back-ticks inside a test.


For a single use script, you could create a lock file in your code:-
Code:
#!/bin/ksh

if [ -f /tmp/my_lock_file ]
then
   cat /tmp/my_lock_file
   exit
fi

# I've got here, so it's not locked by anyone else, so I will lock it

echo "`date` : This script is being run by $USER" >/tmp/my_lock_file

# Do what your script needs to do
# Do what your script needs to do
# Do what your script needs to do
# Do what your script needs to do

# Tidy up lock file
rm /tmp/my_lock_file

It's not pretty, but it works in a clunky way.

You can add more to it to reduce the risk of someone else getting in between you checking and creating the lock file, but it's more complex and doesn't work if you switch user:-
Code:
if [ -f /tmp/my_lock_file ]
then
   echo "Sorry, but \c"
   cat /tmp/my_lock_file
   exit 99
fi
echo "$USER started updates at `date '+%H:%M:%S on %d/%m/%Y'`">/tmp/my_lock_file
sleep 1
cat /tmp/my_lock_file|read luserid rest
if [ $luserid != $USER ]
then
   echo "Very unlucky. \c"
   cat /tmp/my_lock_file
   exit 99
fi


# I've got here, so it's not locked by anyone else, so I will lock it

echo "`date` : This script is being run by $USER" >/tmp/my_lock_file

# Do what your script needs to do
# Do what your script needs to do
# Do what your script needs to do
# Do what your script needs to do

# Tidy up lock file
rm /tmp/my_lock_file

To respond to the suggestions from RavinderSingh13

The problem with looking for a process of the right name is that someone could be editing a file of the same/similar name, or using more to browse the script. They will all get detected as an in-use condition.

It would be neater written as:-
Code:
if [ `ps -ef | grep -c [t]est.ksh` -ne 1 ]
then

... although I'm probably breaking all sorts of rules about back-ticks inside a test.


I hope that this helps
Robin
Liverpool/Blackburn
UK

Last edited by rbatte1; 11-25-2013 at 09:51 AM..
# 4  
Old 11-25-2013
One more way to do it

Code:
#!/bin/sh

myPid=$$
scriptName=$(basename $0)
lockFile=/tmp/${scriptName}.pid

#Check if the lockfile exists. If yes check if the process that locked exists
if [ -f ${lockFile} ] 
then
  pid=$(cat $lockFile)
  if ps -ef | grep -v grep | grep -q ${pid}
  then
    echo "An earlier instance of the script ${scriptName} is running with pid ${pid}."
    exit 1
  else  #The script has exited without removing the lock file.
    rm ${lockFile}
fi

#Now create the new lockfile
echo ${myPid} >$l{lockFile}

Make sure that you remove the lock file when you exit.(Both planned and unplanned exit)
This User Gave Thanks to chacko193 For This Post:
# 5  
Old 11-25-2013
...and a good way to ensure that is the trap command.

Code:
# Run this once we know we have the file
trap "rm /path/to/file" EXIT

This User Gave Thanks to Corona688 For This Post:
# 6  
Old 11-25-2013
I suppose it depends if an abort wants to leave it locked up for investigation though.

If not, and you want to leave the lock in place, you would need to share the detail of what to clean up so it can be dealt with promptly if you need to.
# 7  
Old 11-25-2013
Quote:
Originally Posted by rbatte1
For a single use script, you could create a lock file in your code:-
Code:
#!/bin/ksh

if [ -f /tmp/my_lock_file ]
then
   cat /tmp/my_lock_file
   exit
fi

# I've got here, so it's not locked by anyone else, so I will lock it
...

It's not pretty, but it works in a clunky way.
I disagree. It does not work. As you yourself subsequently observed, there is a race condition between the file existence check and file creation (chacko193's suggestion is similarly afflicted).

Quote:
Originally Posted by rbatte1
You can add more to it to reduce the risk of someone else getting in between you checking and creating the lock file ...
Executing more instructions during a race, prolonging the interval during which the process is in a vulnerable state, is exactly what you want to avoid. That just complicates and multiplies unforeseen interactions. If a race cannot be eliminated (this one can), the best strategy is to reduce the window of opportunity as much as possible.

The correct solution requires an atomic operation (such as rename(2), mkdir(2), open(2) with O_CREAT|O_EXCL, etc) to eliminate the race completely.

A race-free solution:
Code:
set -C
if ! >lockfile; then
    # lockfile already exists
fi
set +C

set -C is synonymous with set -o noclobber, and both are POSIX-compliant. If the file exists, with noclobber enabled, the > redirection fails with a non-zero exit status. The noclobber implementation does its best to avoid the race in this thread (using open(2) with O_CREAT|O_EXCL).

When lockfile exists, if it's desirable to silently discard the sh-generated error message, append 2>/dev/null after fi.

Regards,
Alister

Last edited by alister; 11-25-2013 at 04:43 PM.. Reason: Brevity
These 2 Users Gave Thanks to alister For This Post:
 
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

Perl script with lock to execute only once in a day

Hi, I am new to perl and have a script to which i want to ensure that no matter how many ever times i execute the script it should execute only once per day. Cronjob is not a safe method as I want to built in capability inside the script. (1 Reply)
Discussion started by: ctrld
1 Replies

2. Shell Programming and Scripting

Script lock functionality

Hi All, My requirement is i have a script A.sh .When a person A runs the script A.sh it should get locked and person B should not run the script. i followed the below code f_script_lock() { process=$1 user=`ps -ef | grep -i "$process" | grep -i 'ksh' | awk '{print $1;}'` if ; then ... (1 Reply)
Discussion started by: mohanalakshmi
1 Replies

3. Shell Programming and Scripting

Lock the 2nd script!

Hi All, newbie here, is it possible to lock my second script? because my 1st script is still running. Ex. 1st run : 1st script.sh --> running..... 2nd run : 1st script.sh --> lock because the script is still running.. i don't have any idea how to do it. Please advise, Thanks,... (1 Reply)
Discussion started by: nikki1200
1 Replies

4. UNIX for Advanced & Expert Users

Testing privileges -lock lockfile /var/lock/subsys/..- Permission denied

Hi all, I have to test some user priviliges. The goal is to be sure that an unauthorized user can't restart some modules (ssh, mysql etc...). I'm trying to automate it with a shell script but in same cases I got the syslog broadcast message. Is there any way to simply get a return code... (3 Replies)
Discussion started by: Dedalus
3 Replies

5. UNIX for Dummies Questions & Answers

How do i lock a ksh shell script?

Hi, I have a ksh shell script that accesses databases to drop and create tables and the script also creates text files. This shell script is accessed thru a java application that i would like to turn multi-user, but the only way that i can do that is if I can figure out a way to lock the shell... (2 Replies)
Discussion started by: ndedhia1
2 Replies

6. Shell Programming and Scripting

Large password lock script

I am trying to create a script that will take a very large, tab delimited file and then lock accounts. File headers look like this id desc server pass sudo lock test Test user server01 67 no no "Test user" is under the desc column Basically if pass column is greater... (5 Replies)
Discussion started by: Gibby13
5 Replies

7. Red Hat

Security Question: Lock after invalid login, Session Lock and Required Minimum Password Length

Hello all, If anyone has time, I have a few questions: How do I do the following in Linux. We are using Red Hat and Oracle Enterprise Linux, which is based on Red Hat too. 1. How to lock the account after a few (like 3) invalid password attempts? 2. How do you lock a screen after 30... (1 Reply)
Discussion started by: nstarz
1 Replies

8. Shell Programming and Scripting

How to write a directory lock shell script?

Hi there, pleas I want this script urgently. how to lock a directory by shell script? (12 Replies)
Discussion started by: joneggk
12 Replies

9. Shell Programming and Scripting

Lock for this script

Hi, My requirement is to service a process and below is the script which i wrote for that and works fine, I have kept it in a crontab and running this everyminute, how do I lock this if its already running and i dont want to open if its running and not completed yet. The crontab need to run... (4 Replies)
Discussion started by: strunz
4 Replies

10. UNIX for Dummies Questions & Answers

how to lock keyboard without using lock command

how can I lock my keyboard while I'm away from the computer without using lock command. What other commands gives me the option to lock keyboard device? thanks (7 Replies)
Discussion started by: dianayun
7 Replies
Login or Register to Ask a Question