【问题标题】:Start subshells with assignment and wait for that使用分配启动子shell并等待
【发布时间】:2021-06-09 18:58:28
【问题描述】:

如何通过分配变量启动一些子shell并等待所有完成?

#!/bin/bash

#some code about $FILE="$1"

cat "$FILE" | while read -r HOST || [[ -n $HOST ]];
do
    echo "$HOST";
    URL="http://$HOST";  QUEST1=$(curl -Is --connect-timeout 200 --max-time 200 "$URL" | head -1);
    P1=$!
    URL="https://$HOST"; QUEST2=$(curl -Is --connect-timeout 200 --max-time 200 "$URL" | head -1);
    P2=$!
    
    echo "$P1 $P2"
    wait $P1 $P2
    R1=$( echo "$QUEST1" | grep -o " 200" );
    R2=$( echo "$QUEST2" | grep -o " 200" );
    echo "$R1 $R2"
    
    if [[ "$R1" || "$R2" ]]; then
    echo "FOUND!";
    fi

done

这不起作用。 echo "$P1 $P2" 是空的,因为我在 subshel​​l 中。我希望从当代开始,这样我就不必等待第一次完成。

好的,这是一个基本问题,但我想了解如何将其应用于其他情况。请我不要外部文件。

编辑 谁不明白。我想将$QUEST1 和$QUEST2 放在后台以加快时间并等待完成后不使用额外文件。我读了很多,但没有任何解决办法。谢谢

【问题讨论】:

  • 放置一个有效的 shebang 并将您的脚本粘贴到 shellcheck.net ,另请参阅 How can I read line-by-line or field-by-field 并且似乎没有后台作业,因此 $P? 为空...
  • @Jetchisel “在 shellcheck.net 上放一个有效的 shebang 并粘贴你的脚本”我不习惯这样做。我已经推了,但你看不到它。这里无法上传。说一切都很好。我想你没有读过。我需要分配后台任务,因为执行一些当代动作会更快。每个请求都有一个超时时间,这样时间就大大减少了。如果想将代码放在 shellcheck.com 中,我向上添加了 #!/bin/bash。
  • shellcheck 在循环内或循环后检测到 3 个问题仍然echo "$P1 $P2" is empty because I'm in subshell.?如果在循环之后 - 阅读 mywiki.wooledge.org/BashFAQ/024 并修复 SC2002 将解决您的问题。请阅读How to Ask。 wait $P1 $P2你没有在后台启动任何东西,所以你等不及了。您是否打算添加 & 以在后台运行它? Please i don't want external file. - 请使用外部文件。使用文件是使用 shell 的方式。
  • @KamilCuk “使用文件是使用 shell 的方式。” -> 有变量。 “wait $P1 $P2你没有在后台启动任何东西,所以你等不及了”没关系,但我想在后台做!!似乎那个 shellcheck 它是所有问题的解决方案。这里有人。我想把这 2 个 subshel​​l 放在后台一起等待它们完成。仍然连接事物。这不是答案。谢谢你一样
  • 例如:x=$( { { /bin/sleep 10 ; echo out1; echo out2; } | head -1; } & ); echo $! 将 阻塞 父 shell 十秒钟。并且$! 被正确定义在子shell 中,但它是子shell $!,而不是父shell。要获得预期的$!,您必须通过标准输出、标准错误或文件,或命名管道等传输它。

标签: bash shell


【解决方案1】:

这是cmets的简历:

使用子shell输出(STDOUT)将子shell输出分配给变量/意味着父shell将等待所有子shell子进程的结束,即使有一个内部backgrounded命令。

举个例子:

x=$( { { /bin/sleep 10 ; echo out1; echo out2; } | head -1; } & ); \
echo "Wrong child PID : $!"

这将阻塞父 shell 十秒钟。但是在这里你得到了父 shell $!,而不是子 shell 中定义的那个。要获得预期的$!,您必须以某种方式将其传输到您的父 shell(通过 STDOUT、STDERR 或文件,或命名管道等)。例如,您可以通过 STDOUT 实现这一点:

subpid=$( { { { /bin/sleep 10 ; echo out1; echo out2; } | head -1; } 1>&2 & } ; \
echo $!)

在这里,由于您的子 shell 将其命令输出发送到 STDERR,并且仅在 STDOUT 上输出子 PID $!,因此该命令将几乎立即执行(此时父 shell 不会阻塞 I/O)。

正如您希望尽可能避免 I/O,并且如果您只需要子 shell $! 来等待子进程,您可以依赖父 shell 将等待 所有 STDOUT 的事实子shell的输出。那么你的实际命令就足够了,不需要知道子shell$!:

URL="http://$HOST";  QUEST1=$(curl -Is --connect-timeout 200 --max-time 200 "$URL" \
| head -1);

但是,如果您需要知道子 shell 的子 PID(请注意,此 PIDhere 将是 shell pid,而不是 curl 或 head 命令)并 wait 等待子shell命令完成,然后您可以执行类似的操作来获得接近确定性的顺序(如果您的子命令不包含至少一个管道,则将不起作用):

x=$( { spid=$( { { { /bin/sleep 10;echo out1;echo out2; }|head -1;} 1>&2 & };echo $!);} \
2>&1 ; echo "SUBPID=$spid" )

这将在 10 秒 后提​​供x:SUBPID=<subshell child pid> out1。

此时,这个 SUBPID 将不再存在(或者不再是“您的”子shell 子 pid),但您可以记录它或用它做任何您想做的事情。

您的命令将类似于:

URL="http://$HOST";  QUEST1=$( \
{ subpid=$( { { curl -Is --connect-timeout 200 --max-time 200 "$URL" | head -1; \
 } 1>&2 & } ;echo $!); } 2>&1 ; echo "SUBPID=$subpid" );

QUEST1 中的第一个条目应该是 SUBPID=,然后是 curl 第一行输出。

为了清楚地表明 shell 会等待,您可以在 google.com 中使用 10 秒 sleep 对其进行测试:

URL="http://www.google.com";  QUEST1=$( { subpid=$( \
{ { { curl -Is --connect-timeout 200 --max-time 200 "$URL"; sleep 10; } | head -1; \
 } 1>&2 & };echo $!); } 2>&1 ; echo "SUBPID=$subpid" );

更新

经过我们的交流,我知道您正在一个子shell中寻找一个异步可等待子进程,当它完成时您需要从中获取输出,所有这些不使用临时文件也没有命名管道。

有一种解决方案不需要临时文件,不需要磁盘写入 I/O,并且基于 @hhtamas solution to create an anonymous fifo 用于匿名管道而不是命名管道。

首先,这里是该解决方案的一个简单示例,随后是针对您的用例的实现(许多 curl 调用通过子shell)。

示例解决方案:

#!/bin/bash
# We use the bright solution from @htamas to create an anonymous pipe
# in the fds of our current shell.
# see: https://superuser.com/questions/184307/bash-create-anonymous-fifo
#
#
# 1. Creating the anonymous pipe
#

# start a background pipeline with two processes running forever
tail -f /dev/null | tail -f /dev/null &
# save the process ids
PID2=$!
PID1=$(jobs -p %+)
# hijack the pipe's file descriptors using procfs
exec 3>/proc/"${PID1}"/fd/1 4</proc/"${PID2}"/fd/0
# kill the background processes we no longer need
# (using disown suppresses the 'Terminated' message)
disown $PID2
kill "${PID1}" "${PID2}"
# anything we write to fd 3 can be read back from fd 4

#
# 2. Launching an "asynchonous subshell" and get its output
#

# We set a flag to trap the async subshell termination through SIGHUP
ready=0;
trap "ready=1" SIGHUP;

# We launch our subshell for the subprocess "sleep 10" with its output
# connected to the standalone anonymous pipe.
# As the sleep command as no output, we add "starting" and "finish".
# Note that as we send the output elsewhere than STDOUT, it's non blocking
# Note also that we send SIGHUP to our parent shell ($$) when the command finishs.
x=$( { echo "starting"; sleep 10; echo "finish"; echo "EOF"; kill -SIGHUP $$; } >&3 & )

# We now wait that our subshell terminates, it will terminate within the sleep command.
# Will waiting, we can do stuff. Here we just display "Waiting.." every seconds.
while [ "${ready}" = "0" ]; do
   echo "waiting for subshell..";
   sleep 1;
done;

# We close fd 3 early as we should no more output from the subshell
exec 3>&-

# We recover our subshell output from the out point of the autonomous pipe in y
line=""
y=$( while [ "${line}" != "EOF" ] ; do 
      read -r -u 4 line; 
      [ "${line}" != "EOF" ] && echo "${line}"; 
     done );

# And display the output of the subshell
echo "Subshell terminate, its output : ";
echo "${y}"

# close the file descriptors when we are finished (optional)
exec 4<&-

此解决方案需要/proc 文件系统,这在许多实际的 UNIX 中很常见。解释在脚本中以 cmets 的形式提供。

次要编辑: 更好的子shell 标识过程,等待时的更多进程信息,处理子shell 的潜在崩溃。

为您的用例实现:

#!/bin/bash
#
# Create the anonymous pipe.
# 
# Parameters: None.
# Returns:
#   0 : Success.
#   1 : Failed to launch tails.
#   2 : Failed to exec.
#   3 : Failed to kill tails process.
function CreateAnonymousPipe() {
  # We use the bright solution from @htamas to create an anonymous pipe
  # in the fds of our current shell.
  # see: https://superuser.com/questions/184307/bash-create-anonymous-fifo
  #
  local pid1
  local pid2
  # start a background pipeline with two processes running forever
  tail -f /dev/null | tail -f /dev/null &
  [ $? != 0 ] && return 1;
  # save the process ids
  pid2=$!
  pid1=$(jobs -p %+)
  # hijack the pipe's file descriptors using procfs
  exec 3>/proc/"${pid1}"/fd/1 4</proc/"${pid2}"/fd/0
  [ $? != 0 ] && return 2;
  # kill the background processes we no longer need
  # (using disown suppresses the 'Terminated' message)
  disown "${pid2}"
  kill "${pid1}" "${pid2}"
  [ $? != 0 ] && return 3;

  # anything we write to fd 3 can be read back from fd 4
  return 0;
}
#
# Launch asynchronuously a curl process in a subshell.
# 
# Parameters: { URL } { indice }
#   URL : URL for the curl call.
#   indice : numeric identifier for this call
# Returns:
#   0 : Success.
#   1 : Missing parameters
#   2 : Failed to launch curl subprocess.
#   3 : Failed to access /proc
# STDOUT: PID of the corresponding subshell if success.
function CallCurl() {
  if [ $# != 2 ] ; then
    echo "CallCurl: URL and indice parameter are mandatory." 1>&2
    echo "          CallCurl { URL } { indice }." 1>&2
    return 1;
  fi
  [ ! -d /proc ] && return 3;
  local url="$1"
  local indice="$2"
  local subshell_PID
  # We launch our subshell for the subrprocess curl with its output
  # connected to the standalone anonymous pipe.
  # The curl process output is prefixed with its indice in the URL arrays.
  # Note that the subshell first renames itself with a specific identifier, 
  # curl_<indice>, and that we escape $BASHPID to use its pid for that :
  #   1) We can't use $$ to get the subshell PID as it is not a shell variable that
  #      can be evaluated at execution. As it is "immutable" from the shell point of
  #      view, it'll be always evaluated at first expansion, thus the parent shell PID.
  #   2) We don't rename after subshell launch using $! as its PID, at this time the
  #      subshell could have already terminated and its possible that another process
  #      have since been launched with this PID.
  # Note that we send its output elsewhere than STDOUT (to >&3), so it's non blocking.
  # Note also that we send USR1 signal to our parent shell ($$) when the command finishs.
  subshell_PID=$( { { local my_pid; 
                      eval my_pid="\${BASHPID}";
                      printf 'curl_%s' "${indice}">/proc/"${my_pid}"/comm 2>/dev/null;
                      curl -Is --connect-timeout 200 --max-time 200 "${url}" | head -1 |
                      { read -r line; echo "${indice}: ${line}"; };
                      kill -USR1 $$; 
                    } >&3 & 
                  } ; 
                  echo $!; )
  [ $? != 0 ] && return 2;
  echo "${subshell_PID}"
  return 0;
}
#
# Main URL processor, launch curl subprocess asynchronuously.
# 
# Parameters: { URL ... }
#   URL : URL to call with curl.
# Returns:
#   0 : Success.
#   1 : URL parameter(s) missing
#   2 : Failed to launch curl subprocess.
#   2 : Failed to create anonymous pipe.
# STDOUT: Processing and the outputs of the curl commands
function CurlProcessor() {
  if [ $# = 0 ] ; then
    echo "CurlProcessor: URL parameter is mandatory."  1>&2
    echo "               CurlProcessor { URL ... }." 1>&2
    return 1;
  fi
  local indice=0
  local isalive=0
  local -a URLarray
  # Feed the URL array
  while [ $# -gt 0 ] ; do URLarray+=("$1"); shift; done
  # Initialize a set of flags for each URL
  local -a ready
  for ((indice=0; indice < ${#URLarray[@]}; indice++)) ; do ready+=(0); done
  # Initialize an array of subshell PID for each URL to monitor
  local -a pid
  for ((indice=0; indice < ${#URLarray[@]}; indice++)) ; do pid+=(0); done
  # Initialize an array of subshell output for each URL 
  declare -a output
  for ((indice=0; indice < ${#URLarray[@]}; indice++)) ; do output+=(""); done
  # We create the anonymous pipe
  CreateAnonymousPipe
  [ $? != 0 ] && return 3;
  # Set a trap to catch USR1 and check which subshell are still alive through /proc
  # Local handler for the signals
  function trap_handler() {
    for indice in "${!pid[@]}" ; do
      if [ "${pid[${indice}]}" != "0" ] ; then 
        isalive="$(cat /proc/"${pid[${indice}]}"/comm 2>/dev/null)" 2>/dev/null; 
        [ "${isalive}" != "curl_${indice}" ] && ready[${indice}]=1;
      fi
    done
  }
  trap trap_handler USR1 2>/dev/null;
  # Now launch all the subshell
  for ((indice=0; indice < ${#URLarray[@]}; indice++)) ; do
    pid[${indice}]=$(CallCurl "${URLarray[${indice}]}" "${indice}"); 
    [ $? != 0 ] && return 2;
  done
  # We now wait that our subshells terminate.
  # Will waiting, we can do stuff. Here we just display "Waiting.." every seconds.
  local all_finished=0
  local num_finished=0
  local last_num_finished=0
  local direct_check_timer=0
  while [ "${all_finished}" = "0" ]; do
     # We check each URL subshell flag and loop till there is at least one unfinished.
     all_finished=1
     num_finished=0
     for ((indice=0; indice < ${#ready[@]}; indice++)) ; do 
       if [ ${ready[${indice}]} = 0 ] ; then
         all_finished=0; 
       else
         ((num_finished++));
       fi
     done
     echo "waiting for subshells.. ${num_finished}/${#ready[@]} finished.";
     sleep 1;
     # In case one or more subshell have crashed and thus wont send the USR1 signal, 
     # we launch here the handler to check the states of the subshells after 5sec
     # if there is no subshell termination in the interval.
     if [ "${all_finished}" = "0" ] ; then
       if [ "${last_num_finished}" = "${num_finished}" ] ; then
         ((direct_check_timer++))
         if [ "${direct_check_timer}" = "5" ] ; then
             echo "More than 5 seconds with no progress, doing a direct check."
             direct_check_timer=0 
             trap_handler
         fi
       else
         direct_check_timer=0 
       fi
     fi
     last_num_finished="${num_finished}"
  done;
  # All subshell have finished, we send EOF in the autonaumous pipe
  echo "EOF" >&3
  # We close fd 3 early 
  exec 3>&-
  # We recover our subshells outputs from the out point of the autonomous pipe
  local line=""
  local control=""
  while [ "${line}" != "EOF" ] ; do 
    read -r -u 4 line; 
    if [ "${line}" != "EOF" ] ; then
      # Each line should have "indice: " as a prefix to identify the URL associated
      indice="${line/: */}"
      if [ "${indice}" ] ; then
        control="${indice/[0-9]*/}"
        if [ "${control}" = "" ] ; then
          if [ "${output[${indice}]}" != "" ] ; then
            output[${indice}]="${output[${indice}]}\n${line/[0-9]*: /}"
          else
            output[${indice}]="${line/[0-9]*: /}"
          fi
        fi
      fi
    fi
  done
  # close the file descriptors when we are finished (optional)
  exec 4<&-
  # And display the output of the subshells
  echo "Subshells have all terminated, the output : ";
  for ((indice=0; indice < ${#URLarray[@]}; indice++)) ; do 
    echo "Output from URL ${URLarray[${indice}]} :"
    echo "${output[${indice}]}"
  done
  return 0;
}
#
# An example call of CurlProcessor
#
CurlProcessor "http://www.google.com" "http://stackoverflow.com/" "http://en.cppreference.com/"

通过示例调用,您将获得以下输出:

等待子壳.. 0/3 完成。 等待子壳.. 3/3 完成。 子壳已全部终止,输出: URL http://www.google.com 的输出: HTTP/1.1 200 正常 从 URL http://stackoverflow.com/ 输出: HTTP/1.1 301 永久移动 从 URL http://en.cppreference.com/ 输出: 找到 HTTP/1.1 302

当fastly is down,你会得到:

等待子壳.. 0/3 完成。 等待子壳.. 2/3 完成。 等待子壳.. 2/3 完成。 等待子壳.. 2/3 完成。 等待子壳.. 2/3 完成。 等待子壳.. 2/3 完成。 等待子壳.. 2/3 完成。 超过5秒没有进展,直接做检查。 等待子壳.. 2/3 完成。 等待子壳.. 2/3 完成。 等待子壳.. 2/3 完成。 等待子壳.. 2/3 完成。 等待子壳.. 2/3 完成。 超过5秒没有进展,直接做检查。 等待子壳.. 2/3 完成。 等待子壳.. 2/3 完成。 等待子壳.. 2/3 完成。 等待子壳.. 2/3 完成。 等待子壳.. 2/3 完成。 超过5秒没有进展,直接做检查。 等待子壳.. 3/3 完成。 子壳已全部终止,输出: URL http://www.google.com 的输出: HTTP/1.1 200 正常 从 URL http://stackoverflow.com/ 输出: HTTP/1.1 503 后端不可用,连接超时 从 URL http://en.cppreference.com/ 输出: 找到 HTTP/1.1 302

(测试脚本的最佳时间^^。)

【讨论】:

  • 为了清楚地表明 shell 会等待,您可以在 google.com 中使用 10 秒睡眠测试它:@Zilog80 尝试使用 google.com URL="http://www.google.com"; QUEST1=$( { subpid=$( { { { curl -Is --connect-timeout 200 --max-time 200 $URL; sleep 1; } | head -1; } 1&gt;&amp;2 &amp; };echo $!); } 2&gt;&amp;1 ; echo "SUBPID=$subpid" ); 的最后一个示例(澄清)有subpid。作品。向上
  • 命令后echo $QUEST1 的输出是什么?
  • 工作锅。打扰一下。我的输出 4 echo $QUEST1 非常完美。谢谢@Zilog80
  • 您可以存储并等待它例如:{ { sleep 10; } 1&gt;&amp;2 &amp; } ;echo "waiting for $!"; wait $!。如果您使用1&gt;&amp;2 &amp;“剪切” STDOUT,则 bash shell 将不会等待子 shell 终止。但是您可以使用正确的$! 稍后再等待...
  • “我已经为你的目标添加了一个解决方案”“小修改”@这次想说你停下来!好代码。时间太长了。我不是匿名管道、嵌套函数、陷阱(音乐)、索引、isalive 的爱好者。在我的脚本案例(已完成)中,我只添加了一个文件 pid。它等待,因为所有 curl 调用 HTTP 和 HTTPS 完成。它和你的一样快,但更简单。 /proc/"${PID1}"/fd对于谁想要使用它的美丽实现。但这不适合我。我没有任何信息给你我不测试这个文件。但同样感谢^^。你是个傻瓜。这个答案很荒谬。出去玩:)
【解决方案2】:

使用@Zilog80 技术从我自己解决

=====================================

编辑:

这个帖子全错了。

需要外部文件。

=====================================

附:看看他的回答就明白了(关于 STDOUT 1>&2 的重要部分,所以你不会创建错误的孩子)

我知道在 subshel​​l ( ) 中,您可以分配从外部脚本中读出的变量。

在大括号中分组代码块没有子shell。 curl 中的命令是匿名函数{ }。 (参考https://tldp.org)


所以这个时候你可以写

( export QUEST2=$(curl -Is --connect-timeout 2 --max-time 2 $URL | head -1) ) 2&gt;&amp;1 &amp; P2=$!

我有子shell的PID并且任务完成了。

所有代码将是:


#!/bin/bash

FILE="$1"

cat "$FILE" | while read -r HOST || [[ -n $HOST ]];
do
    echo "$HOST";
    URL="http://$HOST";  ( export QUEST1=$(curl -Is --connect-timeout 2 --max-time 2 $URL | head -1) ) 2>&1 & P1=$!
    URL="https://$HOST"; ( export QUEST2=$(curl -Is --connect-timeout 2 --max-time 2 $URL | head -1) ) 2>&1 & P2=$!

    
    echo "$P1 $P2"
    wait $P1 $P2
    R1=$( echo "$QUEST1" | grep -o " 200" );
    R2=$( echo "$QUEST2" | grep -o " 200" );
    echo "$R1 $R2"
    
    if [[ "$R1" || "$R2" ]]; then
    echo "FOUND!";
    fi

done

$FILE 是 textfile.txt,其中包含类似主机/ip 的列表

google.com
software.net
hacking.org
nasa.gov

现在你可以启动你的脚本来尝试一个站点是否有 http 或 https 协议处于活动状态

(USELESS LIKE NO OTHER :() --> 是为了了解如何分叉好

TNKS 到 @Zilog80。

【讨论】:

  • 看看你的答案,看来你明白了。无论如何,请参阅我对 STDOUT 的评论,这是重要的部分。
  • @Zilog80 “看看你的答案,看来你明白了。无论如何,看看我对 STDOUT 的评论,这是重要的部分。”现在效果很好。但不能从 subshel​​l 中获取变量.... MMMMMM 。不工作。完成
  • ...如果我使用导出。
  • 从 subshel​​l 中,除了退出代码之外,没有简单的方法可以获取任何变量/值。正如在 cmets 中所说,您可以通过 STDOUT 将值发送到父 shell 或通过 fifo、命名管道等。但不能直接发送。从父 shell 的角度来看,子 shell 本质上是一个孤立的 shell,不应改变父 shell 上下文或变量。
  • @Zilog80 "如果你还需要一个“异步”子shell并在你的父shell中等待它,可以通过信号和管道来获取输出。一个例子:[ !-p ./mypipe ] && mknod ./mypipe p; ready=0; 陷阱 "ready=1" SIGHUP; x=$( { sleep 10; kill -SIGHUP $$; echo "finish" > ./mypipe; } 1>&2 & ) ; while [ "${ready}" = "0" ]; do echo "waiting for subshel​​l.."; sleep 1; done; y =$(cat ./mypipe); echo " Subshel​​l 终止,它的输出:$y";"陷阱对我来说只有音乐而且我没有管子。问题关闭。 (谢谢)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多