In my C program I want to know if my executable is run in foreground like this
$./a.out
or like this
$./a.out &
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you are the foreground job,
or
STDIN_FILENOorSTDERR_FILENOor 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/SIGTTOUif you just want a quick check.On the other hand, you may have been backgrounded
or foregrounded
at any point in time. You cannot expect that you can check this once and it will still be true (or false) later.