[英]How to get the multiple child process exit status whether it is failed or success in linux shell scripting
如何單獨返回或獲取子進程的退出狀態。
這是子進程
process()
{
rem=$(( $PID % 2 ))
if [ $rem -eq 0 ]
then
echo "Number is even $PID"
exit 0
else
echo "Number is odd $PID"
exit 1
fi
echo "fred $return"
exit $rem
}
for i in {1..100}; do
process $i &
PID="$!"
echo "$PID:$file"
PID_LIST+="$PID "
done
for process in ${PID_LIST[@]};do
echo "current_PID=$process"
wait $process
exit_status=$?
echo "$process => $exit_status"
done
echo " The END"
我期望的是每個偶數退出狀態必須為 0,奇數退出狀態必須為 1。但上面的腳本給出了以下輸出,其中少數偶數退出狀態為 1,少數奇數退出狀態為 0。可以有人糾正我。
16687:
16688:
/home/nzv1dtr/sample_file.sh: line 3: % 2 : syntax error: operand expected (error token is "% 2 ")
16689:
Number is odd 16687
16690:
Number is even 16688
16691:
Number is odd 16689
current_PID=16687
16687 => 1
current_PID=16688
16688 => 1
current_PID=16689
Number is even 16690
16689 => 0
current_PID=16690
16690 => 1
current_PID=16691
16691 => 0
這里還有一些事情要做。 基本上你是在正確的軌道上, wait
可以收集和報告孩子的返回狀態,如下所示:
for i in {0..20}; do
if [[ $((i % 2)) -eq 1 ]]; then
/bin/true &
else
/bin/false &
fi
a[${i}]=$!
done
for i in ${a[@]}; do
wait ${i}; echo "PID(${i}) returned: $?"
done
為什么你看到的不一樣?
嗯,對於初學者來說, process
不是(真的)進程,而是一個函數(因此正如評論中提到的, exit
不是終止它的正確方法,如果在腳本中調用,它將終止整個腳本,而不僅僅是功能)。 它確實成為一個過程,但如何成為它的一部分。 Shell 將生成一個新的子 shell 並運行您的函數(因此退出對外部腳本來說不是致命的)。 你的 shell 在它產生時的狀態在這里很重要。
您還在與${PID}
進行比較,后者實際上是最后一個子 shell 的PID
並且第一次調用會產生錯誤。 您可能想要查找$$
,除了上面的段落意味着,所有函數(子外殼)都將使用相同的值(父進程的)。
配備了這些信息,對您的腳本的最小更改是在process
函數中使用$$
,導出該函數以便我們可以在我們fork
的新 shell 實例中使用它,我們跟蹤該新 shell 的PID
:
process()
{
rem=$(( $$ % 2 ))
...
}
export -f process
for i in {1..100}; do
bash -c "process" $i &
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.