Operating System - HP-UX
1753865 Members
7489 Online
108809 Solutions
New Discussion юеВ

Re: shell quesition: How can I tell whether script is running in background?

 
SOLVED
Go to solution
Jack C. Mahaffey
Super Advisor

shell quesition: How can I tell whether script is running in background?

I want to put a short script together that can be executed to determine if the calling script is currently running in background rather than interactive.

I've got a menu script that goes into a loop if the script inadvertantly runs in background mode. I suspect the connection is being lost in a citrix session.

I want to put in a code check that will terminate the script if it is not currently interactive.

Perhaps the following will be sufficient?
BASENAME=`/usr/bin/basename $0`
ps -ef | grep " $$ " | grep $BASENAME | grep -v "ps -ef" | grep -v grep | grep "?"


jack...
5 REPLIES 5
Chris Wilshaw
Honored Contributor
Solution

Re: shell quesition: How can I tell whether script is running in background?

Quick and dirty test which should work.

if [ `tty | grep not | wc -l` = 1 ];
then
export BACKGROUND=YES
else
export BACKGROUND=NO
fi

This checks to see if there's a controlling tty for the job - if not, assume that it's running in the background (eg. via cron).

the $BACKGROUND parameter can then be used to exit/continue.
Rodney Hills
Honored Contributor

Re: shell quesition: How can I tell whether script is running in background?

You could see if stderr is assigned to a terminal.

if [[ -t 3 ]] ; then
echo "I am running in interactive"
else
echo "I am running in batch"
fi

-- Rod Hills
There be dragons...
MANOJ SRIVASTAVA
Honored Contributor

Re: shell quesition: How can I tell whether script is running in background?

Hi Jack

This will be good as you are trying to check on the current terminal session and then of course

export A=`ps -ef | grep " $$ " | grep $BASENAME | grep -v "ps -ef" | grep -v grep | grep "?" `
kill -9 $A


Manoj Srivastava
Ceesjan van Hattum
Esteemed Contributor

Re: shell quesition: How can I tell whether script is running in background?

I'm not sure, but if you start a script within a shell as a background process, the shell will fork and run the script in a child-shell.

PID=A PPID=B -sh
PID=C PPID=A -sh
PID=D PPID=C $BASENAME

So i should be possible to look whether or not the shell running the program was forked or not. In case the shell was forked, you program is running in backupground.

Hope it will help you.
Regards,
Ceesjan

Jack C. Mahaffey
Super Advisor

Re: shell quesition: How can I tell whether script is running in background?

Really good solutions. Thanks... jack...