0

I'm using lsof command to run only one instance of setup.sh and it works fine if there are no argument values. But, i needed to pass arguments in setup.sh for e.g.

setup.sh machine1 setup.sh machine2 setup.sh machine3

So if setup.sh machine1 is running and again same command runs, it will wait till setup.sh machine1 completes. I think lsof is for process and might not be possible but any other good suggestion for waiting logic?

When i try to pass some argument lsof command gives syntax error, i tried below but no luck. My purpose is run only one instance using machine1 and if anyone try to run setup.sh with machine1 argument then it should wait. Any other file lock/waiting logic?

if ( [[ $(lsof -t \setup.sh 'machine1'| wc -l) > 1 ]] ); then
if ( [[ $(lsof -t '\setup.sh machine1'| wc -l) > 1 ]] ); then
if ( [[ $(lsof -t "\setup.sh machine1"| wc -l) > 1 ]] ); then

Working:

if ( [[ $(lsof -t \setup.sh| wc -l) > 1 ]] ); then
   echo -e "\tWaiting for 2 minutes...\n"
   sleep 2m
else
   echo -e "\tFree now to run setup.sh\n"
fi

Doesn't work (syntax error):

if ( [[ $(lsof -t \setup.sh machine1| wc -l) > 1 ]] ); then
   echo -e "\tWaiting for 2 minutes...\n"
   sleep 2m
else
   echo -e "\tFree now to run setup.sh\n"
fi
Jitesh Sojitra
  • 3,655
  • 7
  • 27
  • 46

2 Answers2

1

You can search processes with arguments using ps -eo args like the following.

ps -eo args | grep '^setup.sh machine1' | wc -l

You need to change grep pattern to suit your case.

thatseeyou
  • 1,822
  • 13
  • 10
0

Greg's Wiki has a great article on process management, particularly "How do I make sure only one copy of my script can run at a time?". lsof is not a reliable way of guaranteeing that only one process is running, because there's a race condition between checking the output of lsof and continuing. If two processes start almost at the same time it is likely that they will both run in parallel.

l0b0
  • 55,365
  • 30
  • 138
  • 223