How does a shell know if it's in the foreground or the background?

Kartik Subbarao subbarao at phoenix.Princeton.EDU
Thu Apr 25 23:24:44 AEST 1991


In article <1991Apr24.232959.6247 at elroy.jpl.nasa.gov> pjs at euclid.jpl.nasa.gov writes:
>One of our users asked this and I'm stumped.  You have a script and
>you want to know whether the user is sitting there at the terminal
>waiting with baited breath for it to complete or whether the hyperactive
>creature typed an "&" after it and went on with other work.  I thought
>I could just test $prompt, but that only tells me whether I've
>source'd a script or not.  How can a csh script know whether it's on
>the job list?  

In shells that support job control (like csh), jobs are put into different 
process group than the parent shell to facilitate job control. The process 
group of the controlling tty is that of the current (foreground) job. What
your shellscript can do is to check whether the script's pgrp (or pid, for
that matter, since it's a group leader) matches the pgrp of the tty. If
they match, then the job is in the foreground. Otherwise, it's a background
job. Here is some sample code that does this:

/* pgrp.c */

# include <stdio.h>
main()
{
	printf("%d\n", tcgetpgrp(0); 
}

Compile this program, and call it within your shellscript:

#!/bin/csh 

if (`pgrp` == $$) then
	echo foreground
else
	echo background
endif


				-Kartik

--
internet# rm `df | tail +2 | awk '{ printf "%s/quotas\n",$6}'`

subbarao at phoenix.Princeton.EDU -| Internet
kartik at silvertone.Princeton.EDU (NeXT mail)  
SUBBARAO at PUCC.BITNET			          - Bitnet



More information about the Comp.unix.questions mailing list