When a process is started with "&", bash places the new process to foreground group for a short time and then places itself back to foreground group.
As far as I know, when we run any external command without the "&" background operator, the shell creates a new process group for the command and notifies the terminal that this process group is now in the foreground. When we run with "&", foreground process group MUST NOT change.
I used a C program on linux which just prints foreground process group and own process group on start and then prints the same after a sleep.
I get the following results:
tcgetpgrp=19981 getpgrp=19981
sleep(5)
tcgetpgrp=11996 getpgrp=19981
In this example 11996 is the pid of bash.
I only noticed this behavior when run as (./test&)
and under heavy load (never as ./test&
).
Is bash behaving the right way?
Bash version: 4.4.12
EDIT
Added pid value as suggested by @Costi:
tcgetpgrp=29148 getpgrp=29148 getpid=29149
sleep
tcgetpgrp=28566 getpgrp=29148 getpid=29149
28566 is pid of bash
(...)
creates a subshell in bash. As per bash manual:
(list) list is executed in a subshell environment (see COMMAND EXECUTION ENVIRONMENT below)
My guess is you are seeing the PID of that subshell as the foreground process, not the PID of your test
command. And the subshell exits quite quickly (right after firing your command in background).
To validate this, add the value returned by getpid
to the mix and check if that is the same as your getpgrp
value when run in a subshell.