while 读循环 +在 while 循环中创建一个进程
下面的测试脚本有问题。当我在脚本中添加行 (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
The following test script has a problem. When I add the line (sleep 5 )&
in the script then the while read
loop does not read all lines from the file, but only prints the first line.
But when I remove the ( sleep 5 )&
from the script, then the script prints all lines as defined in the file.
Why the ( sleep 5 )&
causes this?
And how to solve the problem? I want to create a new process (for which the sleep is just an example) in the while loop.
$ 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您提供的代码运行并打印文件中的每一行。
由于您没有等待
子进程,因此它对进程执行没有影响。这是您编写的确切代码吗?
The code you provides runs and prints each line in the file.
Since you are not waiting for the
child process, it has no effect on process execution. Is this the EXACT code you wrote?
这似乎是特定版本的 ksh 中的错误。我从 ksh 93s+ 获得了相同的效果,但从 bash、ash、pdksh、zsh 或 ksh 93t+ 获得了相同的效果。
This seems to be a bug in a specific version of ksh. I'm getting the same effect from ksh 93s+, but not from bash, ash, pdksh, zsh or ksh 93t+.
这个 KornShell (ksh) 脚本在这个版本中对我来说工作得很好:
echo $KSH_VERSION
@(#)MIRBSD KSH R48 2013/08/16
soExample.ksh:
soExample.ksh 输出:
This KornShell (ksh) script works fine for me with this version:
echo $KSH_VERSION
@(#)MIRBSD KSH R48 2013/08/16
soExample.ksh :
soExample.ksh Output: