i have this line of code on a korn shell script to detect the presence of script run:
ISRUNNING=`ps -eaf -o args | grep -i sfs_load_file.ksh | grep -v grep | wc -l`
sometimes this returns either 1, 2, or 3. when it returns 2 or 3 that tells us that there are more than 1 script of sfs_load_file.ksh runs at the same time. when in reality there is none. i suppose that when i run the sfs_load_file.ksh the variable $ISRUNNING should return only 1 that is because there are none other sfs_load_file.ksh is running.
please help and advise. the code might need some tweak or corrections.
thanks so much,
warren
You can also fuser the script file, which even detects peopel who source the script ('bash <script' or '. script').
Actually it should return 0 if there are 0 processes.
Try this one:
ps -eo args | grep -ic "sfs_load_file[.]ksh"
BTW one can supress the ps header:
ps -eo args= | grep -ic "sfs_load_file[.]ksh"
1 Like
Case sensitivity is OK, so 'grep -c' not grep -ic'. The meta characters '[]' escaping the '.' keep it from being counted. LINUX users have 'pgrep -c sfs_load_file.ksh'
Still misses sourced runs, or someone running it through a link or sym-link. The fuser tactic is slower, but gets everyone on the inode. That just leaves people running it through a copy of a different name.
1 Like
that works thanks so much
Even in pgrep it makes sense to escape the "wildcard dot":
pgrep -c "sfs_load_file[.]ksh"
The standard way is to use a PID file. When you run the script, save its PID in a file. That way you can check
if [ -s pidfile ] && ps `cat pidfile` >/dev/null
then
echo running
else
echo not running
fi
Much nicer than the ps | awk | sed | cut | kitchen | sink nonsense.
pidfiles have their own pitfalls ( pidfalls ).
For example, they must be at a volatile location like the /var/run/ that some Unix provide.
If the program in question has a directory containing data files it uses, the directory containing those data files might work. In many cases, /tmp
is a reasonable place for PIDfiles.