How can a process detect if its 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