How do I know if an C program's executable is run in foreground or background?
问题 In my C program I want to know if my executable is run in foreground like this $./a.out or like this $./a.out & 回答1: If you are the foreground job, getpgrp() == tcgetpgrp(STDOUT_FILENO) or STDIN_FILENO or STDERR_FILENO or whichever file descriptor you're attached to your controlling terminal by. (If you're not sure, open("/dev/tty") will always get you a file descriptor to your controlling terminal, if one exists.) This is what openssh does, and is a bit easier than handling SIGTTIN/SIGTTOU