views:

66

answers:

4

How can my program detect how it was started: by someone using the command-line or by another process?

The program has an optional interactive part that I want to suppress when it was started by another process - running in the background; but when it was started from a terminal I want it to do the interactive bit.

[edit] If it is possible to do from a C++ program.

+1  A: 

Usually, just provide command-line arguments that the caller can use to run in non-interactive mode. You can do fancier things, but that's pretty common -- a lot of times, it -q for quiet.

Lou Franco
okay, might be usable. i'll think on it. I know i've seen somewhere a program/script doing something to detect if it was started from a terminal ... I had a copy, but it went to the great-big-bitbucket-in-the-sky, an event which gave rise to my question on this site on backups.
slashmais
+1  A: 

Bash has a simple test that will tell you if the script was started from a TTY:

if [ -t 0 ]; then
    echo "Interactive code goes here"
fi
JKG
+3  A: 

Check if your stdin isatty, eg

if (isatty(0))
{
    /* interactive! */
}
Hasturkun
This won't work unless the invoking program redirects stdin.
Darron
+1  A: 

<unistd.h> defines the isatty function that you could use to check if the input (0) or output (1) file descriptors are connected to a terminal (which means it is an interactive session).

florin