Queen
Queen

Reputation: 571

Execute a code for 5 seconds and then stop it

The goal of code is that, I want to make a random tcp traffic using iperf and capture it over 5, 10, 15, 20 seconds using tcpdump. In addition, capturing the throughput is also important for me. My problem is that, I would like to execute code1, code2, code3 and code4 for 5, 10, 15 and 20 seconds in bash. However I don't know how to put the mentioned condition for it. Here is my code:

  for Test_duration in 5 10 15 20
    do
    echo “Test performing with $Test_duration duration”

    sudo tcpdump -G 10 -W 2 -w /tmp/scripttest_$Test_duration -i h1-eth0 &

    while true; do

    #code1
    time2=$(($RANDOM%20+1))&
    pksize2=$(($RANDOM%1000+200))&
    iperf -c 10.0.0.2 -t $time2 -r -l $pksize2  >> /media/sf_sharedsaeed/throughtput/iperthroughput_host2_$Test_duration.txt &\

    #code2
    time3=$(($RANDOM%20+1))&
    pksize3=$(($RANDOM%1000+200))&
    iperf -c 10.0.0.3 -t $time3 -r -l $pksize3  >> /media/sf_sharedsaeed/throughtput/iperthroughput_host3_$Test_duration.txt &\

    #code3
    time4=$(($RANDOM%20+1))&
    pksize4=$(($RANDOM%1000+200))&
    iperf -c 10.0.0.4 -t $time4 -r -l $pksize4  >> /media/sf_sharedsaeed/throughtput/iperthroughput_host4_$Test_duration.txt &\

    #code4
    time5=$(($RANDOM%20+1))&
    pksize5=$(($RANDOM%1000+200))&
    iperf -c 10.0.0.5 -t $time5 -r -l $pksize5  >> /media/sf_sharedsaeed/throughtput/iperthroughput_host5_$Test_duration.txt &\

    done

    done

Another constraint is that, code1, code2, code3 and code4 should be executed at the same time so, I used &. Please help me what should I replace instead of while true; to have periodic execution of codes. Can any body help me?

Upvotes: 0

Views: 285

Answers (1)

user3837712
user3837712

Reputation:

You could do that by using a background subshell that creates a simple file lock on expiration that you detect from your while loops. Here is an example based on a simplified version of your code:

for Test_duration in 5 10 15 20
do
  # TIMEOUT_LOCK will be your file lock
  rm -f TIMEOUT_LOCK
  # next command will run in a parallel subshell at the background
  (sleep $Test_duration; touch TIMEOUT_LOCK) &
  echo “Test performing with $Test_duration duration”
  while true; do
    # check whether current timeout (5 or 10 or 15 ...) has occured
    if [ -f TIMEOUT_LOCK ]; then rm -f TIMEOUT_LOCK; break; fi
    # do your stuff here - I'm just outputing dots and sleeping
    echo -n "."
    sleep 1
  done
  echo ""
done

The output of this code is:

“Test performing with 5 duration”
.....
“Test performing with 10 duration”
..........
“Test performing with 15 duration”
...............
“Test performing with 20 duration”
....................

Upvotes: 1

Related Questions