在Linux中,如何让一个shell脚本以多进程的模式同时并行运行多份?

有时候,想让一个shell脚本像多进程模式那样并行运行多份,同时又能统一管理和终止。此时使用pipexec是最佳选择。

debian有该包,直接apt安装即可【1】。其它可能需要自行下载源代码并编译【2】。

以下是一个命令行示例,用于将test-sleep.sh并行运行5次:

pipexec \
-k \
-p /var/run/pipexec-test-sleep.pid \
-- \
[Test1 /bin/bash test-sleep.sh ] \
[Test2 /bin/bash test-sleep.sh ] \
[Test3 /bin/bash test-sleep.sh ] \
[Test4 /bin/bash test-sleep.sh ] \
[Test5 /bin/bash test-sleep.sh ]

其中,参数p用于写入运行pipexec时的pid,这个在用于服务管理的时候很有用。

注意,使用pipexec有可能会创建复杂的递归子进程,故使用ps命令行终止pipexec父进程无效,此时的表现为pipexec被终止运行了,但创建的相关子进程并不会被连环终止。要终止整个pipexec下面的所有子进程,尤其是递归子进程,需要使用pstree命令,详细见本站文章《Linux如何查看或杀死指定进程的所有子进程(包括递归子进程)?》【3】。

【1】https://packages.debian.org/stable/pipexec

【2】https://github.com/flonatel/pipexec

【3】https://www.orztip.com/?p=542&article_title=pstree-show-or-kill-process-dependency

本页永久链接:https://www.orztip.com/?p=548&article_title=pipexec-run-shell-script-as-multi-process