Where is the second process from

Put the following code in a shell script, for example. x.sh and chmod + x x.sh

./x.sh

what i expect is there is only one line, but in fact I have 2 lines:

tmp $ ./x.sh
52140 ttys003    0:00.00 /bin/sh ./x.sh
52142 ttys003    0:00.00 /bin/sh ./x.sh

My question is: where do 52142 come from?

#!/bin/sh
myself=$(basename $0)
running=$(ps -A | grep "$myself" |grep -v grep)
echo "${running}"

Note: this is on macOS 10.12

Updated question using a new experiment:

#!/bin/sh
myself=$(basename $0)
running=$(ps -fe | grep $myself |grep -v grep)

echo ==== '$(ps -fe | grep "$myself" |grep -v grep)' ====
echo "${running}"
echo 

running=$(ps -fe | cat)
echo ==== '$(ps -fe | cat) |grep $myself' ====
echo "${running}"|grep $myself
echo 

running=$(ps -fe)
echo ==== '$(ps -fe) |grep $myself' ====
echo "${running}" |grep $myself

Exit on MacOS 10.12:

==== $(ps -fe | grep "$myself" |grep -v grep) ====
  501 59912 81738   0  9:01AM ttys003    0:00.00 /bin/sh ./x.sh
  501 59914 59912   0  9:01AM ttys003    0:00.00 /bin/sh ./x.sh

==== $(ps -fe | cat) |grep $myself ====
  501 59912 81738   0  9:01AM ttys003    0:00.00 /bin/sh ./x.sh
  501 59918 59912   0  9:01AM ttys003    0:00.00 /bin/sh ./x.sh

==== $(ps -fe) |grep $myself ====
  501 59912 81738   0  9:01AM ttys003    0:00.00 /bin/sh ./x.sh

From above it seems that the subshell is also connected to the pipe.

+4
source share
1 answer

$(command)- command substitution. commandwas executed in a subshell.

A subman is a child process (fork) of the original shell (or shell script), if you check with ps, part of the file name matches the original (parent) shell script.

, x.sh :

echo "$(ps -fe --forest>foo.txt)"

--forest ps . foo.txt search x.sh, .

, :

kent     20866   707  0 15:55     \_ urxvt 
kent     20867 20866  0 15:55         \_ zsh
kent     21457 20867  0 15:56             \_ sh ./x.sh
kent     21459 21457  0 15:56                 \_ sh ./x.sh #subshell
kent     21460 21459  0 15:56                     \_ ps -fe --forest

, script :

(
echo "$(ps -fe --forest>foo.txt)"
)

x.sh , foo.txt:

... 25882 27657  0 16:05 ...  \_ -zsh
... 31027 25882  0 16:16 ...      \_ sh ./x.sh
... 31028 31027  0 16:16 ...          \_ sh ./x.sh #subshell1
... 31029 31028  0 16:16 ...              \_ sh ./x.sh #subshell2
... 31031 31029  0 16:16 ...                  \_ ps -fe --forest

$PPID.

+4

Source: https://habr.com/ru/post/1676160/


All Articles