简体   繁体   English

使用bash脚本分发命令行

[英]Distributing lines of commands using bash script

I'm trying to implement trivial parallelization where lines of commands are distributed among separate processes. 我正在尝试实现简单的并行化,其中命令行分布在不同的进程中。 For that purpose I wrote this script that I named jobsel : 为此我写了这个脚本,我命名为jobsel

(only "#! /bin/bash" and help message is omitted)

slots=$1
sel=$2

[[ $slots -gt 0 ]] || die_usage
[[ $sel -lt $slots ]] || die_usage

i=0
while read line
do
        (( i % slots == sel )) && eval $line
        i=$(( i + 1 ))
done

# in case the last line does not end with EOL
if [[ $line != "" ]]; then
        (( i % slots == sel )) && eval $line
        i=$(( i + 1 ))
fi

I put eval because I couldn't use redirection or pipe in the commands without it. 我把eval因为没有它我不能在命令中使用重定向或管道。

When I run this like $HOME/util/jobsel 22 0 < cmds on a console emulator when cmds is a file that contains lines like echo 0 >> out with increasing numbers, it outputs, as expected, 0, 22, 44... in separate lines. 当我在控制台模拟器上运行这个像$HOME/util/jobsel 22 0 < cmds时,当cmds是一个包含echo 0 >> out和更多数字的行的文件时,它会按预期输出$HOME/util/jobsel 22 0 < cmds 0, 22, 44...在单独的行。 Good so far. 目前很好。

So I put this to work. 所以我把它付诸实践。 But when I ran this through secure shell, I ran it through at with backgrounding (ending each line with & ). 但是,当我跑这通过安全壳,我跑它通过at与backgrounding(截止到每一行& )。 Then there is a problem. 然后有一个问题。 When I entered 8 lines, 21 processes started! 当我输入8行时,开始了21个进程! ps -AFH printed processes with identical command and different pIDs. ps -AFH打印的进程具有相同的命令和不同的pID。 All work processes were at the same level, directly under init. 所有工作流程都直接在init下处于同一级别。 My program does not create child processes anyway. 我的程序无论如何都不会创建子进程。

Puzzled, I tried the echo 0 >> out script through at then the output contained duplicate lines. 困惑,我尝试了echo 0 >> out脚本at然后输出包含重复的行。 Still finding it hard to believe, and thinking simultaneous appending might have caused the anomaly, I used other methods to confirm that some lines were run multiple times. 仍然觉得很难相信,并且考虑同时追加可能会导致异常,我使用其他方法来确认某些行已经多次运行。

Moreover, there was no such anomaly when everything was run in terminal or when I created separate at job for each worker process. 此外,当所有东西都在终端中运行或者我为每个工作进程创建单独at工作时,没有这样的异常。

But how can this happen? 但这怎么可能发生呢? Is something wrong with my script? 我的脚本有问题吗? Does at/atd have some bug? at/atd有一些错误吗?

GNU parallel is what you are trying to implement. GNU parallel是你想要实现的。

Hint : it works great combined to xargs 提示:它与xargs结合得非常好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM