问题描述
我想使我的code的部分更有效。我想使它叉关闭到多个进程,并让他们在执行一次次50/100的,而不是只一次。
I would like to make a section of my code more efficient. I'm thinking of making it fork off into multiple processes and have them execute 50/100 times at once, instead of just once.
例如(伪):
for line in file;
do
foo;
foo2;
foo3;
done
我想这个循环多次运行。我知道这与派生来完成。难道是这个样子?
I would like this for loop to run multiple times. I know this can be done with forking. Would it look something like this?
while(x <= 50)
parent(child pid)
{
fork child()
}
child
{
do
foo; foo2; foo3;
done
return child_pid()
}
还是我想这个错误的方式?
Or am I thinking about this the wrong way?
谢谢!
推荐答案
在的bash脚本(非交互)默认情况下禁用作业控制,所以你不能做的命令:工作,FG和BG
In bash scripts (non-interactive) by default JOB CONTROL is disabled so you can't do the the commands: job, fg, and bg.
下面是很适合我:
#!/bin/sh
set -m # Enable Job Control
for i in `seq 30`; do # start 30 jobs in parallel
sleep 3 &
done
# Wait for all parallel jobs to finish
while [ 1 ]; do fg 2> /dev/null; [ $? == 1 ] && break; done
最后一行使用FG带来了后台作业到前台。它这样做是在一个循环,直到FG返回1($?== 1),当其不再有任何更多的后台作业它。
The last line uses "fg" to bring a background job into the foreground. It does this in a loop until fg returns 1 ($? == 1), which it does when there are no longer any more background jobs.
这篇关于分叉/多线程进程|巴什的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!