Am I in background? Isatty(3) won't tell you!

Ray Lubinsky rwl at uvacs.UUCP
Thu Nov 21 02:43:21 AEST 1985


> It sounds (from text not quoted here) like what you really want to know
> is whether the standard input is the user's terminal.  Phrased that
> way, you've prob'ly already realised the easy way:
> 
> #define STDIN	0
> 
> 	if (isatty(STDIN)) ...
> 
:
> 	Joe Yao		hadron!jsdy at seismo.{CSS.GOV,ARPA,UUCP}

Actually, this won't do the trick.  If the original poster wanted to know
whether the process has pipes into and out of it, then this is the method.
However, child- and parent-processes may share stdin, stdout, etc.  Try running

	#include <stdio.h>
	main() { printf("I am in the %sground.\n",(isatty(0))?"fore":"back"); }

in the background if you don't believe me.

A preferable method was posted by some time ago by (geez, I didn't save the
net address) and restated below:

	#include <sys/ioctl.h>

	foregroundp()
	{
		int	tpgrp;	/* short in 4.1, int in 4.2 */

		if (ioctl(0,TIOCGPGRP,&tpgrp))
			return(0);
		return(tpgrp == getpgrp(0));
	}

This will work for all combinations of ``backgrounding'' and I/O redirection
execpt that it incorrectly returns non-zero when you run the command from the
command line and redirect stdin.
-- 

Ray Lubinsky		     University of Virginia, Dept. of Computer Science
			     uucp: decvax!mcnc!ncsu!uvacs!rwl



More information about the Comp.unix.wizards mailing list