How can a process detect if it's running in the background?

How can a process detect if it's running in the background?

First of all: do you want to know if you're running in the
background, or if you're running interactively? If you're
deciding whether or not you should print prompts and the like,
that's probably a better criterion. Check if standard input
is a terminal:

sh: if [ -t 0 ]; then ... fi
C: if(isatty(0)) { ... }

In general, you can't tell if you're running in the background.
The fundamental problem is that different shells and different
versions of UNIX have different notions of what "foreground" and
"background" mean - and on the most common type of system with a
better-defined notion of what they mean, programs can be moved
arbitrarily between foreground and background!

UNIX systems without job control typically put a process into the
background by ignoring SIGINT and SIGQUIT and redirecting the
standard input to "/dev/null"; this is done by the shell.

Shells that support job control, on UNIX systems that support job
control, put a process into the background by giving it a process
group ID different from the process group to which the terminal
belongs. They move it back into the foreground by setting the
terminal's process group ID to that of the process. Shells that
do *not* support job control, on UNIX systems that support job
control, typically do what shells do on systems that don't
support job control.



Home FAQ