Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash pgrep-P$$提供了一个不存在的进程id_Bash_Pid_Subshell_Bash Trap - Fatal编程技术网

Bash pgrep-P$$提供了一个不存在的进程id

Bash pgrep-P$$提供了一个不存在的进程id,bash,pid,subshell,bash-trap,Bash,Pid,Subshell,Bash Trap,它输出 #!/usr/bin/env bash sleep 3 & # Spawn a child trap ' pgrep -P $$ # Outputs one PID as expected PIDS=( $( pgrep -P $$ ) ) # Saves an extra nonexistant PID echo "PIDS:

它输出

#!/usr/bin/env bash
sleep 3 &                               # Spawn a child

trap '
    pgrep -P $$                         # Outputs one PID as expected
    PIDS=( $( pgrep -P $$ ) )           # Saves an extra nonexistant PID
    echo "PIDS: ${PIDS[@]}"             # You can see it is the last one
    ps -o pid= "${PIDS[@]:(-1)}" ||
    echo "Dafuq is ${PIDS[@]:(-1)}?"    # Yep, it does not exist!

' 0 1 2 3 15
它只发生在陷阱中。 为什么将不存在的PID追加到数组中?如何避免这种奇怪的行为?

通过使用
$(…)
,您已经创建了一个子流程来执行该代码

当然,该进程的父进程将是当前shell,因此它将被列出

至于解决方法,您可以从列表中删除该PID。首先,您必须知道如何访问子shell PID:。现在您可以过滤掉它(不,它不起作用):


问题是,如果陷阱不存在,奇怪的行为就会消失。这可能与bash中
trap
的实现方式有关。。但我没有心情深入研究源代码,这是肯定的..:我想是的,但是如何避免仍然困扰着我。这是一个类似的问题,经常出现:你没有测试过我的建议吗?谢谢Karoly,第一个很有用。因此,是的
$(pgrep-P$$)
产生了奇数进程。编辑:对不起,我打错了,但无论如何我还是错了。所以一个解决方法是手动删除子shell进程id,有更好的方法吗?
11800
PIDS: 11800 11802
Dafuq is 11802?
PIDS=( $( pgrep -P $$ | grep -v ^$BASHPID$ ) )