ps -ef


 
Thread Tools Search this Thread
Top Forums UNIX for Advanced & Expert Users ps -ef
# 1  
Old 06-16-2006
ps -ef

Hi

In a script we are checking if any other instance of the same script is running to make sure that we don't run multiple threads, and if there is only one then we are proceeding otherwise coming out of it ..
To do this we check as below,
ps -ef | grep -i 'scriptname' | grep -v grep | wc -l

this at times returns 2, but when I try to display
ps -ef | grep -i 'scriptname' | grep -v grep

it shows only the current instance that is getting started ..
Can anyone please help me in figuring out the problem.

Many thanks
# 2  
Old 06-16-2006
If you are using solaris or linux (and possibly other *NIXs) you could use:

Code:
pgrep scriptname | grep -v $$

In your script. If any lines are returned another instance of the script is running.
# 3  
Old 06-16-2006
scripts usually run external programs. This means they must fork() and then exec(). If you catch it after the fork and prior to the exec, you will see two processes. Also be aware that a pipeline like this:
one | two | three
will involve multiple forks.
# 4  
Old 06-16-2006
Sorry, forgot to mention about one important thing though ..

this script works fine if we run it normally, but when the script is called after a server reboot (automatically called as part of unix start up) , it says it can see 2 processes with the name 'scriptname' but lists only one , that is the one which its correctly starting ..

Any help would be really appreciated.
# 5  
Old 06-16-2006
Thanks Perdarabo ..
Looks like I understand what you are saying ..
So if my script is called runMonitor.sh, then are you saying that if i give
ps -ef | grep -i 'runMonitor.sh' | grep -v grep | wc -l

will invoke 1 fork for each command that has the name 'runMonitor.sh' ?

sorry I posted this query in advanced column , but I am quite comfortable in unix commands but not in the way they are executed..
So please help
# 6  
Old 06-16-2006
I'm sure pgrep will suit your needs ... here is an example script. You cant have it running more than once one a single machine.

Put the following codes intoa script called 'sleep.sh'

Code:
#!/bin/sh
# sleep.sh: test running a single instance of a script
pgrep sleep.sh | grep -v $$ > /dev/null

# if we were already running exit
if [ $? -eq 0 ]
then
  echo sleep.sh is already running exiting ...
  exit
fi

sleep 1000

# 7  
Old 06-16-2006
I personally have a preference for using pid lockfiles.
Login or Register to Ask a Question

Previous Thread | Next Thread
Login or Register to Ask a Question