arrays - 在 ksh 脚本中获取数组中的 pid
问题描述
我正在使用 ksh 创建一个脚本,其中执行一个进程 (simple_script.sh) 并迭代 5 次。我需要做的是每次执行进程时获取 pid 并将它们存储在数组中。到目前为止,我可以让脚本执行 simple_script.sh 5 次,但无法将 pid 放入数组中。
while [ "$i" -lt 5 ]
do
./simple_script.sh
pids[$i]=$!
i=$((i+1))
done
解决方案
正如 Andre Gelinas 所说,$!
存储最后一个后台进程的 pid。
如果你对所有并行执行的命令都满意,你可以使用这个
#!/bin/ksh
i=0
while [ "$i" -lt 5 ]
do
{ ls 1>/dev/null 2>&1; } &
pids[$i]=$!
i=$((i+1))
# print the index and the pids collected so far
echo $i
echo "${pids[*]}"
done
结果将如下所示:
1
5534
2
5534 5535
3
5534 5535 5536
4
5534 5535 5536 5537
5
5534 5535 5536 5537 5538
如果要串行执行命令,可以使用wait
.
#!/bin/ksh
i=0
while [ "$i" -lt 5 ]
do
{ ls 1>/dev/null 2>&1; } &
pids[$i]=$!
wait
i=$((i+1))
echo $i
echo "${pids[*]}"
done
推荐阅读
- docker - 在生产中处理码头工人和容器
- sympy - 总和,展开条款
- javascript - removeEventListner() 不生效
- php - PHP 发布请求(CURL、JSON)不工作
- c++ - 如何正确从 nalgebra::Matrix 转换为 Eigen::MatrixXf?
- sql-server - 检查我在 SQL Server 上的数据库实例是否被 TDE 加密?
- java - 仅用于组的 Libgdx 相机
- python-sphinx - RST 条件指令不能使用标准语法
- scala - 如何在 spacemacs 中正确安装 scala metal lsp
- python-3.x - 有人可以帮我弄清楚为什么终端(MacOS)将不再找到我保存的 python 文件吗?