|
Posted by Peter J. Holzer on July 28, 2008, 10:42 am
Please log in for more thread options > \
>> Would it help to have an indication whether you're in the foreground or
>> in the background?
>> Usually background processes aren't connected to a terminal, most
>> important, STDIN won't be connected to a terminal
This is wrong in general.
>> as then two processes (the current "foreground" process and the
>> "background" process) contend for the input from the keyboard,
That's why about 20 years ago, Unixes started to stop background
processes from reading from the terminal (see the SIGTTIN signal).
>> so you could check whether STDIN is a
>> terminal.
Won't work.
> that's what I thought and so did a -t STDIN, but it shows true whether
> in the foreground or background.
Right. STDIN doesn't change. You can flip a process between foreground
and background (in most shells with the conveniently named commands "fg"
and "bg"), but it would be rather messy if that changed an open file
descriptor. What changes is whether the process group is the foreground
process group of the controlling terminal. The place to look for
POSIX (=UNIX) specific functionality is the POSIX module:
| getpgrp This is identical to Perl’s builtin "getpgrp()" function for
| returning the process group identifier of the current process,
| see "getpgrp" in perlfunc.
[...]
| tcgetpgrp
| This is identical to the C function "tcgetpgrp()" for returning
| the process group identifier of the foreground process group of
| the controlling terminal.
If they are the same we should be in the foreground:
% perl -MPOSIX -le 'print getpgrp() == tcgetpgrp(STDIN) ? "foreground" :
"background"'
foreground
% perl -MPOSIX -le 'print getpgrp() == tcgetpgrp(STDIN) ? "foreground" :
"background"' & sleep 1
[1] 23462
background
[1] + done perl -MPOSIX -le
Looks good.
hp
|