【问题标题】:while read loop + create aproccess in the while loopwhile 读取循环 + 在 while 循环中创建进程
【发布时间】:2011-03-05 23:50:21
【问题描述】:

以下测试脚本有问题。当我在脚本中添加(sleep 5 )& 行时,while read 循环不会从文件中读取所有行,而只会打印第一行。

但是当我从脚本中删除 ( sleep 5 )& 时,脚本会打印文件中定义的所有行。

为什么( sleep 5 )& 会导致这种情况?

以及如何解决这个问题?我想在while循环中创建一个新进程(sleep只是一个例子)。

$ more test

#!/bin/ksh 
while read -r line ; do 
echo $line
( sleep 5 )&   
RESULT=$!
sleep 1
kill $RESULT
done < file


$ more file
123 aaa
234 bbb
556 ccc

【问题讨论】:

  • 您使用的是哪个版本的 ksh?我没有像 Gilles 提到的那样在 ksh93t+ 上看到它

标签: shell unix scripting ksh


【解决方案1】:

您提供的代码运行并打印文件中的每一行。

因为你不是在等待

( sleep 5 ) &

子进程,对进程执行没有影响。这是您编写的确切代码吗?

【讨论】:

    【解决方案2】:

    这似乎是特定版本的 ksh 中的错误。我从 ksh 93s+ 获得了相同的效果,但不是 bash、ash、pdksh、zsh 或 ksh 93t+。

    【讨论】:

      【解决方案3】:

      这个 KornShell (ksh) 脚本在这个版本中很适合我:

      • echo $KSH_VERSION
        • @(#)MIRBSD KSH R48 2013/08/16

      soExample.ksh :

      #!/bin/ksh 
      
      #Initialize Variables
      file=file
      fileContent="123\taaa\n234\tbbb\n556\tccc"
      
      #Function to create File with Input
      #Params: 1}Directory 2}File
      createBlankFileHere(){
          echo "Entering createFileHere"
          > ${1}
          echo "Exiting createFileHere"
      }
      
      #Function to create File with Input
      #Params: 1}File 2}String to write to FileName
      createFileWithInputHere(){
          echo "Entering createFileWithInputHere"
          > ${1}
          #-e means 'enable interpretation of backslash escapes
          echo -e ${2} >> ${1}
          #print ${2} >> ${1}
          echo "Exiting createFileWithInputHere"
      }
      
      #Function to 
      #Params: 1} File
      readLine(){
          echo "Entering readLine"
          while read -r line ; do 
          echo ${line}
          ( sleep 5 )&   
          RESULT=${!}
          sleep 1
          kill ${RESULT}
          done < ${1}
          echo "Exiting readLine"
      }
      
      #-----------
      #---Main----
      #-----------
      echo "Starting: ${PWD}/${0} with Input Parameters: {1: ${1} {2: ${2} {3: ${3}"
      createFileWithInputHere ${file} ${fileContent} #function call#
      readLine ${file} #function call#
      echo "Exiting: ${PWD}/${0}"
      

      soExample.ksh 输出:

      user@foo /tmp
      $ ksh soExample.ksh
      Starting: /tmp/soExample.ksh with Input Parameters: {1:  {2:  {3:
      Entering createFileWithInputHere
      Exiting createFileWithInputHere
      Entering readLine
      123 aaa
      234 bbb
      556 ccc
      Exiting readLine
      Exiting: /tmp/soExample.ksh
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-04
        • 2021-02-20
        • 2018-04-17
        • 2016-11-27
        • 1970-01-01
        • 1970-01-01
        • 2013-07-08
        • 1970-01-01
        相关资源
        最近更新 更多