4

So if I input the command like below, a sub-process (PID 4920) is created by the subshell.

linuxprobe@DESKTOP-TP0G72N:~$ (sleep 2;ps -f --forest;sleep 5)
UID          PID    PPID  C STIME TTY          TIME CMD
linuxpr+     513     512  0 Feb17 pts/0    00:00:00 -bash
linuxpr+    4920     513  0 01:35 pts/0    00:00:00  \_ -bash
linuxpr+    4922    4920  0 01:35 pts/0    00:00:00      \_ ps -f --forest

If I input the command like below, seems no sub-process is created

linuxprobe@DESKTOP-TP0G72N:~$ (ps -f --forest)
UID          PID    PPID  C STIME TTY          TIME CMD
linuxpr+     513     512  0 Feb17 pts/0    00:00:00 -bash
linuxpr+    5511     513  0 01:45 pts/0    00:00:00  \_ ps -f --forest

Why can subshell create a sub-process in the first example?

1 Answer 1

10

It's not a matter of can; both, as you can see, do create a subprocess.

The difference is the in the second case, the last command in the shell is the ps execution.

And because nothing happens after that, your bash decides that instead of exec'ing in a forked process, it can just exec the ps executable in itself, without fork'ing before.

So, not a matter of can, but a matter of choose not to, to optimize.

1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .