[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

RE: shell script: How to determine if I'm in the background?

>I certainly don't want my scripts to exhibit erratic behaviour. Besides,
>I'm not sure how the concept of "interactive" relates to the concept of
>"background", and I dont like the idea of trusting a shell variable that
>may or may not exist in shells other than bash. 

Essentially, the only difference between a process in the foreground and the
background is where it's getting it's data for stdin, and where stdout is
pointing.  This is interactivity.  A valid way of running a program in the
"background" is to ignore SIGINT/SIGQUIT and redirect stdin/out to
/dev/null.  More advanced shells like bash use the concept of process groups
and what not to determine what process is getting input from the tty.  Your
process has no idea this is happening; and neither should it!  Consider a
fairly trivial example :

cat file.txt | more

What does this really do?  It sets up a pipe between fd 1 (stdout) of the
cat process, and fd 0 (stdin) of the more process.  What about

more < file.txt

This opens file.txt and makes it fd 0 of the more process. Both cases are
very different, but In both cases all more is doing is calling read() on fd
0, it has no idea where the data it is getting comes from.  

>If a process can be
>backgrounded on all sorts of unix systems running all kinds of shells,
>then that process should be able to determine if it's in the background
>in all those circumstances.

You're asking the impossible.  There is no definitive way that a program is
run in the "background".  Instead of thinking about bash and how you put a &
after the program and it appears to run "in the background", you need to
understand exactly what the shell is doing to that process (look up
information on the fork() and exec() system calls as a start). 

As I mentioned in a previous email, you're better off either writing two
programs -- one interactive and one not, using common libraries; or put a
flag asking about interactivity.  That way, say, I can put all the commands
I know I want to input into your program in a file called commands.txt and

./program.sh < commands.txt & 

and it works just as fine as if I typed them.  How would your program handle
this case?  

CAUTION: This message may contain confidential information intended only for the use of the addressee named above. If you are not the intended recipient of this message, any use or disclosure of this message is prohibited.  If you received this message in error please notify Mail Administrators immediately.  You must obtain all necessary intellectual property clearances before doing anything other than displaying this message on your monitor.  There is no intellectual property licence.  Any views expressed in this message are those of the individual sender and may not necessarily reflect the views of Woolworths Ltd.

Reply to: