linux - 在 shell 脚本中每秒运行一个 for 循环
问题描述
我试图每秒运行一个程序
for i in {1..3}
do
echo $i `date`
./tt.sh $i &
sleep 1
done
for循环实际上是在后台触发9个循环有没有办法每秒运行程序
下面是过程信息
root 10455 1 0 23:44 pts/0 00:00:00 /bin/bash ./tt.sh 1
root 10458 10455 0 23:44 pts/0 00:00:00 /bin/bash ./tt.sh 1
root 10460 10455 3 23:44 pts/0 00:00:00 /bin/bash ./tt.sh 1
root 10692 1 0 23:44 pts/0 00:00:00 /bin/bash ./tt.sh 2
root 10699 10692 0 23:44 pts/0 00:00:00 /bin/bash ./tt.sh 2
root 10701 10692 2 23:44 pts/0 00:00:00 /bin/bash ./tt.sh 2
root 10943 1 0 23:44 pts/0 00:00:00 /bin/bash ./tt.sh 3
root 10953 10943 0 23:44 pts/0 00:00:00 /bin/bash ./tt.sh 3
root 10955 10943 2 23:44 pts/0 00:00:00 /bin/bash ./tt.sh 3
解决方案
当你看
root 10455 1 0 23:44 pts/0 00:00:00 /bin/bash ./tt.sh 1
root 10458 10455 0 23:44 pts/0 00:00:00 /bin/bash ./tt.sh 1
root 10460 10455 3 23:44 pts/0 00:00:00 /bin/bash ./tt.sh 1
您可以看到tt.sh
使用 pid 10455 启动了另外两个进程。
tt.sh
你的循环已经启动了 3 次,你可以看看tt.sh
它为什么会产生额外的进程。
使用下面的代码,您可以看到该脚本仅启动程序 3 次:
for i in {101..103}
do
echo $i `date`
sleep $i &
sleep 1
done
并将ps -ef
显示
username 39 1 0 09:05 pts/0 00:00:00 sleep 101
username 42 1 0 09:05 pts/0 00:00:00 sleep 102
username 45 1 0 09:05 pts/0 00:00:00 sleep 103
如果您不希望它们同时运行,请删除&
.
推荐阅读
- html - 无法让我的静态样式表使用 django 连接到我的 html
- python - I get different results when calling from Postman and from a Python script
- reactjs - Reactjs - 如何将道具传递给路由?
- amazon-web-services - 如何从 s3 亚马逊存储桶中的 csv 文件中删除列?
- git - 7 位 git commit 哈希是八进制数的概率是多少?
- vue.js - Vue3动态添加组件到dom
- python - 检查一个值是否是 Python 中的任何数字
- c# - 从类的 void 获取字符串值无法正确输出
- javascript - Mongoose deleteMany 在 pre-hook 中,如何访问所有将被删除的文件?
- swift - 使用 @escaping 闭包时创建 Observable 的问题