In my C program I want to know if my executable is run in foreground like this
$./a.out
or like this
$./a.out &
In my C program I want to know if my executable is run in foreground like this
$./a.out
or like this
$./a.out &
To my knowledge this is not possible and usually not necessary either.
Please explain why you want to do this.
[invalid]
IIRC, getppid() (on *nix systems) will give you the parent id. if it is 0, the 'console' is your parent and so you are running in the background.
[/invalid]
[edit]
int devtty;
if ((devtty = open ("/dev/tty", O_RDWR)) < 0)
printf ("daemon\n");
note that this is only valid on *nix systems (and then only if nobody has deleted /dev/tty -- for whatever reason)
[/edit]
From the Bash Reference Manual: Job Control Basics:
Background processes are those whose process group id differs from the terminal's; such processes are immune to keyboard-generated signals. Only foreground processes are allowed to read from or write to the terminal. Background processes which attempt to read from (write to) the terminal are sent a SIGTTIN (SIGTTOU) signal by the terminal driver, which, unless caught, suspends the process.
So the solution is to install a signal handler for SIGTTIN
and then try to read from stdin
(turn buffering off or it will block). If you get "0 bytes read" back, then you're running in the foreground.
[EDIT] Note that the status of a process can change. You can use the job control commands of the shell (Ctrl-Z, bg
, fg
and jobs
) to do this.