aminfar
aminfar

Reputation: 2345

Passing message to an interactive program using bash script

I have written an echoclient and echoserver network program so that messages written on the client side can be echoed to the client by the echoserver program. Echoclient is an interactive program that waits for the user to enter a message. It then sends the message, gets the response, and then again waits for a new message from the user. Now I would like to write a script shell so that I can send a new message to the server every 100 microseconds. But I don't know how to pass messages to the echoclient program. Any thought on that?

#connect to the server ...
./echoclient SERVER_IP_ADDR SERVER_PORT

i=1
while [ 1 ]
do
   #send "message i" to the server. how to do it?
   usleep 100  
   let i++ 
done

Upvotes: 1

Views: 1877

Answers (2)

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74750

Instead of a fifo (which Erik showed), a simple pipe should work too, like this (code stolen from Erik's anwser):

let i=1
while true
do
   echo "message $i"
   sleep 0.001
   let i+=1
done |
./echoclient SERVER_IP_ADDR SERVER_PORT

This way the loop runs in a subshell, though, so you can't access the new value of $i after the loop (it's still 1).

Another way would be to run the echoclient as a bash coprocess, and connect its input to the output of the echo command. (If you want to see the result, too, it would get more complicated.)

Upvotes: 1

Erik
Erik

Reputation: 91270

EDIT: First answer was way off - misread the question. The below mechanism should work.

mkfifo /tmp/echostuff
./echoclient SERVER_IP_ADDR SERVER_PORT < /tmp/echostuff &

exec 3>/tmp/echostuff
let i=1
while true
do
   echo "message $1" >&3
   sleep 0.0001
   let i+=1
done

Upvotes: 2

Related Questions