Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何与bash同时处理文件?_Bash_File_Concurrency - Fatal编程技术网

如何与bash同时处理文件?

如何与bash同时处理文件?,bash,file,concurrency,Bash,File,Concurrency,假设我有10K个文件和一个处理单个文件的bash脚本。现在,我想同时处理所有这些文件,并且只并行运行K脚本。我不想(显然)多次处理任何文件 您建议如何在bash中实现它?I bash您只需使用“(”and“)即可在不同的进程中轻松运行部分脚本。如果添加&,则父进程将不会等待子进程。所以您实际上使用了(command1;command2;command3;…)和: while ... do ( your script goes here, executed in a sep

假设我有10K个文件和一个处理单个文件的
bash
脚本。现在,我想同时处理所有这些文件,并且只并行运行
K
脚本。我不想(显然)多次处理任何文件


您建议如何在
bash
中实现它?

I bash您只需使用“(”and“)即可在不同的进程中轻松运行部分脚本。如果添加
&
,则父进程将不会等待子进程。所以您实际上使用了
(command1;command2;command3;…)和

while ... do
    (
        your script goes here, executed in a separate process

    ) &
    CHILD_PID = $!
done
还有
$为您提供子进程的PID。你还需要知道什么?当到达启动的
k
进程时,需要等待其他进程。这是使用
等待
完成的:

如果您想等待所有这些,只需使用
wait


这应该足以实现系统。

执行有限数量并行作业的一种方法是使用。例如,使用此命令:

find . -type f -print0 | parallel -0 -P 3 ./myscript {1}
您将把当前目录(及其子目录)中的所有文件作为参数传递给
myscript
,一次传递一个文件。
-0
选项将分隔符设置为空字符,
-P
选项设置并行执行的作业数。默认并行进程数等于系统中的内核数。对于集群中的并行处理,还有其他选项,这些都有文档记录


请测试一下。如果K不是太大,请使用不同的进程。这样做的缺点是,一旦启动了
cnt
进程,在所有进程都完成之前,您将无法启动另一个作业。
find . -type f -print0 | parallel -0 -P 3 ./myscript {1}
   for f1 in *;do
      (( cnt = cnt +1 ))
      if [ cnt -le $k ];then
         nohup ./script1 $f1 &
         continue
       fi
       wait
       cnt=0
   done