大网数据广告活动
服务器运维问答

pgrep returns extra processes when piped by other commands

· 52CE 我爱测

Here is a very strange question about using pgrep to search which shell processes are running the same script as the current one. Here is the test script named test.sh #!/bin/bash full_res=`pgrep -a -l -f 'test\.sh'` res=$(pgrep …

问题原文

原帖链接 · machinarium · CC BY-SA 4.0

Here is a very strange question about using pgrep to search which shell processes are running the same script as the current one.

Here is the test script named test.sh

#!/bin/bash

full_res=`pgrep -a -l -f 'test\.sh'`

res=$(pgrep -a -l -f 'test\.sh' | cat)

echo "short result is $full_res"

echo "weird result is $res"

With output being

sh test.sh &
[1] 19992
➜  logs short result is 19992 sh test.sh
weird result is 19992 sh test.sh
19996 sh test.sh

[1]  + 19992 done       sh test.sh

I don't know where the 19996 sh test.sh comes from, especially when using a pipe to cat. I believe it might be a bug to pgrep implementation.

Looking forward to some reasonable explanation

Thx,

Balin

已采纳解答

原帖链接 · Matthew Ife · CC BY-SA 4.0

When you created the pipeline using backticks or $(...) a subshell is created which is an exact copy of the original bash shell you called.

At the point you're doing the pgrep what you actually have is this:

bash test.sh
  └─bash test.sh
      └─ pgrep -f test.sh
      └─ cat

So pgrep is doing what you asked it to.

You can simulate this behaviour like this.

#!/bin/bash
echo mypid $$
$(sleep 60 | sleep 60 | sleep 60)

Run the process in the background, using the pid it spat out, inspect it with pstree.

$ ./test.bash 
mypid 335153
^Z
[1]+  Stopped                 ./test.bash
$ bg
[1]+ ./test.bash &
$ pstree -p 335153
test.bash(335153)───test.bash(335154)─┬─sleep(335155)
                                      ├─sleep(335156)
                                      └─sleep(335157)

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2023-04-13)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。