The reason why that happens is because enabling job control (set -m
) brings along not just process grouping, but also the machinery for handling "foreground" and "background" jobs. This "machinery" implies that each command run in turn while job control is enabled becomes the foreground process group.
Therefore, in short, when that sub-shell (the left part of your pipeline) enables job control it literally steals the terminal from the entire pipeline, which had it until then and which, in your example, includes the less
process, thus making it become background and, as such, not allowed to use the terminal any more. It therefore gets stopped because less
does keep accessing the terminal.
By issuing fg
you give the terminal back to the entire pipeline, hence to less
, and all ends well. Unless you run additional commands within the job-controlling sub-shell, because in such case each additional command would steal the terminal again.
One way around it is to simply run your job-controlled sub-sub-shell in background:
( set -m; (
$1
) & set +m ) |
(
$2
)
You will have the command expressed by $1
run in its distinct process group as you wish, while the backgrounded mode prevents stealing the terminal, thus leaving it to the pipeline and hence to $2
.
Naturally this requires that the command in $1
does not want to read the terminal itself, otherwise it will be the one to get stopped as soon as it attempts to do it.
Also, likewise to as I said above, any additional job-controlled sub-sub-shell you might like to add would require the same "backgrounding" treatment, all along until you set +m
, otherwise each additional job-controlled sub-sub-shell would steal the terminal again.
That said, if all you need process grouping for is to kill processes, you might consider using pkill
to target them. For instance pkill -P
will send a signal to the processes whose parent is the indicated PID. This way you can target all children (but not grand-children) of your sub-process by just knowing the sub-process's PID.
current terminal process group ID
mentioned in the documentation. I don't know the mechanics good enough to write a decent answer, but maybe this comment will allow you to advance your research. – Kamil Maciorowski May 18 '20 at 19:45