问题描述
基本上,我正在尝试退出包含循环的子外壳.这是代码:`
Basically, I am trying to exit a subshell that contains a loop. Here is the code:`
stop=0
( # subshell start
while true # Loop start
do
sleep 1 # Wait a second
echo 1 >> /tmp/output # Add a line to a test file
if [ $stop = 1 ]; then exit; fi # This should exit the subshell if $stop is 1
done # Loop done
) | # Do I need this pipe?
while true
do
zenity --title="Test" --ok-label="Stop" --cancel-label="Refresh" --text-info --filename=/tmp/output --font=couriernew # This opens Zenity and shows the file. It returns 0 when I click stop.
if [ "$?" = 0 ] # If Zenity returns 0, then
then
let stop=1 # This should close the subshell, and
break # This should close this loop
fi
done # This loop end
echo Done
这不起作用.它从不说完成.当我按下停止"按钮时,它只是关闭对话框,但继续写入文件.
This does not work. It never says Done. When I press Stop it just closes the dialog, but keeps writing to the file.
我需要能够将变量从子Shell传递到父Shell.但是,我需要继续写入文件并保持"Zenity"对话框出现.我该怎么办?
I need to be able to pass a variable from the subshell to the parent shell. However, I need to keep writing to the file and keep the Zenity dialog coming up. How would I do this?
推荐答案
生成子shell时,它将创建当前shell的子进程.这意味着,如果您在一个外壳中编辑变量,则该变量将不会反映在另一个外壳中,因为它们是不同的进程.我建议您将子外壳发送到后台,并使用$!
获取其PID,然后在准备就绪时使用该PID杀死该子外壳.看起来像这样:
When you spawn a subshell, it creates a subprocess of the current shell. This means that if you edit a variable in one shell, it will not be reflected in the other, because they are different processes. I suggest you send the subshell to the background and use $!
to get its PID, then use that PID to kill the subshell when you're ready. That would look like this:
( # subshell start
while true # Loop start
do
sleep 1 # Wait a second
echo 1 >> /tmp/output # Add a line to a test file
done # Loop done
) & # Send the subshell to the background
SUBSHELL_PID=$! # Get the PID of the backgrounded subshell
while true
do
zenity --title="Test" --ok-label="Stop" --cancel-label="Refresh" --text-info --filename=/tmp/output --font=couriernew # This opens Zenity and shows the file. It returns 0 when I click stop.
if [ "$?" = 0 ] # If Zenity returns 0, then
then
kill $SUBSHELL_PID # This will kill the subshell
break # This should close this loop
fi
done # This loop end
echo Done
这篇关于如何退出子shell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!