【问题标题】:Shell: Return value of a non-child processShell:非子进程的返回值
【发布时间】:2013-01-04 11:13:43
【问题描述】:

在 shell 脚本中,我试图等待非子进程。我得到了关于如何做到这一点的参考: WAIT for "any process" to finish

我的shell脚本结构是:

Main.sh

func1(){
return 1
}

func2(){
# Wait for func1 to finish
while kill -0 "$pid_func1"; do
      sleep 0.5
done
}
# Call function 1 in background
func1 &
pid_func1=$!
func2 &

在这种情况下,我如何在函数 func2 中接收 func1 的返回值?

【问题讨论】:

  • 只是为了澄清,这个例子是问'如何等待子进程',但你的问题的标题是问如何获得非子进程的返回值。实际的问题是什么?如果您问我能否从非子进程中获取返回码,那么它通常不可用

标签: shell parallel-processing return-value kill


【解决方案1】:

您通常无法捕获非子进程的退出状态。您可能可以进行一些涉及将退出代码记录到状态文件然后读取值的工作,但否则您将无法捕获值

【讨论】:

  • 我也在后台调用func2。而且我收到错误“pid不是这个shell的孩子”。
  • 在这种情况下它不会工作 - 你不能等待不是当前 shell 的子任务
【解决方案2】:

在这种情况下,我使用了另一个 shell 变量来存储返回状态,并在需要时检查了这个 shell 变量的值。在下面找到一个示例 shell 脚本来模拟场景。

#!/bin/bash

func1(){
retvalue=23 # return value which needs to be returned
status_func1=$retvalue # store this value in shell variable
echo "func1 executing"
return $retvalue
}



func2(){
# Not possible to use wait command for pid of func1 as it is not a child of func2
#wait $pid_func1
#ret_func1=$?

while kill -0 "$pid_func1"; do
      echo "func1 is still executing"
      sleep 0.5
done

echo "func2 executing"

#echo "func1 ret: $ret_func1"
echo "func1 ret: $status_func1"
}

# Main shell script starts here

func1 &
pid_func1=$!

func2 &

希望它对面临同样问题的其他人有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    • 2017-11-27
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    相关资源
    最近更新 更多