views:

1463

answers:

5

My $SHELL is tcsh. I want to run a c shell script that will call a program many times with some arguments changed each time. The program I need to call is in Fortran; I don't want to edit it. The program only takes arguments once the it is executed, but not on the command line. Upon calling the program in the script the program takes control (this is where I am stuck currently, I can never get out because the script will not execute anything untill after the program process stops), at this point I need to pass it some variables, then after several iterations I will need to ctrl-c out of the program and continue with the script. How?

A: 

Not a tcsh user, but if the program runs then reads in commands via stdin then you can use shell redirection < to feed it the required commands. If you run it in the background with & you will not block when it is executed. Then you can sleep for a bit, then use whatever tools you have (ps, grep, awk, etc) to discover the program's PID, then use kill to send it SIGTERM which is the same as doing a ctrl-c.

freespace
+1  A: 

Uhm, can you feed your Fortran code with a redirection? You can create a temporary file with your inputs, and then pipe it in with the stdin redirect (<).

Toybuilder
+2  A: 

What you want to use is Expect.

tvanfosson
Oh, I had forgotten about Expect! Excellent answer!
Toybuilder
+3  A: 

To add to what @Toybuilder said, you can use a "here document". I.e. your script could have

./myfortranprogram << EOF
first line of input
second line of input
EOF

Everything between the "<<EOF" and the "EOF" will be fed to the program's standard input (does Fortran still use "read (5,*)" to read from standard input?)

And because I think @ephemient's comment deserves to be in the answer:

Some more tips: <<'EOF' prevents interpolation in the here-doc body; <<-EOF removes all leading tabs (so you can indent the here-doc to match its surroundings), and EOF can be replaced by any token. An empty token (<<"") indicates a here-doc that stops at the first empty line.

I'm not sure how portable those ones are, or if they're just tcsh extensions - I've only used the <<EOF type "here document" myself.

Paul Tomblin
Some more tips: <<'EOF' prevents interpolation in the here-doc body; <<-EOF removes all leading tabs (so you can indent the here-doc to match its surroundings), and EOF can be replaced by any token. An empty token (<<"") indicates a here-doc that stops at the first empty line.
ephemient
A: 

This is a job for the unix program expect, which can nicely and easily interactively command programs and respond to their prompts.

wnoise