I need to run a programmme, let say ./a for 10 times in the linux shell. What is the command to do that?
Also, how could I differentiate the output from different pr开发者_StackOverflow中文版ocesses?
Besides, my ./a is a continual process. How could I terminate it?
Thanks.
In bash you can do:
for ((i=1;i<=10;i++)); do
# run the command ./a and redirect its output to a file named after
# its sequence number...like out1.txt, out2.txt...
./a > out$i.txt &
done
The key here is the &
which runs the command in the background. Without the &
the 2nd ./a
will be started after the fist got completed, effectively making it serial execution. But with &
, we don't wait for one invocation of ./a
to complete before we launch another one and that is how we achieve parallelism.
Make a loop that starts the program 10 times in the background:
for i in $(seq 1 10) ; do
./a &
done
Also, how could I differentiate the output from different processes?
You can't easily do that, the output can be interwined. Redirect the output of each process to a different file rather, e.g.
for i in $(seq 1 10) ; do
./a >output.$i &
done
As a oneliner, you'd run
for i in $(seq 1 10) ; do ./a >output.$i & done
to kill those processes later:
for i in $(seq 1 10) ; do kill %$i ; done
for i in {1..10}
do
./a > "out_${i}.txt" &
done
to terminate a
, you can use pkill a
Assuming you use Bash or compatible shell, the special variable $!
holds the process ID of the last process you made asynchronous. Augumenting nos' answer, I'd suggest using
for i in $(seq 1 10) ; do
./a 1> stdout.$i 2> stderr.$i &
echo $! > pid.$i
done
Now you have error output in stdout.X
, error output in stderr.X
and the process ID in pid.X
so you can kill it with
kill `cat pid.X`
or even kill all processes with
for i in $(seq 1 10) ; do
kill `cat pid.$i`
done
All of the other answers are fine so far, but you amy also want to try repeat
, if supported by your system:
repeat 10 ./a
Here to differentiate outputs, unfortunately, you won't be able to use a counter variable. You can however use a timestamp:
repeat 10 ./a >> output_`date +%N`
That being said, the behavior of date
for anything below the second mark is unspecified, so that's not the most reliable way. A bit easier than to write a for
loop though.
精彩评论