tags:

views:

76

answers:

2

In C, what is the way to detect a program was called in "background mode" ? I have a program I would like to launch either interactively or in background.

How can I detect I should not be reading from stdin and end in a "Stopped : tty input" state ?

Should I test that stdin is closed ? How can I do that ?

Edit : isatty seems like a good idea, but what happen if stdin is a pipe end, and not a tty ?

+1  A: 

1) You should check if stdin is open, and open /dev/null to it if it closed.

2) You can use isatty which "returns 1 if desc is an open file descriptor connected to a terminal and 0 otherwise"

Douglas Leeder
+2  A: 

Use the tcgetpgrp() function on the file descriptor of the controlling terminal (e.g. STDIN_FILENO or 0 for stdin) to check whether the current foreground process group is equal to your own process group (from getpgrp()). However the foreground process group could change at any time, as your program is moved between foreground and background. For example, it could change immediately after you call tcgetpgrp() and before you test it. So keep this in mind if you are going to take any action based on this; it is not a reliable method of avoiding SIGTTIN.

#include <unistd.h>
pid_t fg = tcgetpgrp(STDIN_FILENO);
if (fg == -1) {
    /* stdin is not controlling terminal (e.g. file, pipe, etc.) */
} else if (fg == getpgrp()) {
    /* foreground */
} else {
    /* background */
}
mark4o