Take the 2-minute tour ×

Hey all. I'm trying to translate a simple bash script that executes a program (called pdb2gmx) into C commands so I can include it as a function in a much larger program, but I'm having some trouble making it happen.

The bash script:

/usr/local/gromacs/bin/pdb2gmx -f ${1}.pdb -o ${1}.gro -p ${1}.top << EOF

So what's going is that when running the program, it stops and asks for user input at two separate points, one right after the other. In the bash script, just putting down 14 and 6 seems to fulfill the input requirement, but I can't seem to pull off the same trick in C (also, I'm not really sure what the EOF is doing there, I'm just following someone else's example with that, and the script won't work without it).

This is what I have so far in C:

#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE * pdb2gmx;
    pdb2gmx = popen( "pdb2gmx -f 1BEO.pdb -o 1BEO.gro -p 1BEO.top" , "w" );
    fprintf( pdb2gmx, "EOF" );
    fprintf( pdb2gmx, "14" );
    fprintf( pdb2gmx, "6" );
    pclose( pdb2gmx );

but when this code is executed pdb2gmx just hangs at the first point where it needs user input. So what am I missing?

My sense is that the C program itself is also hanging on the execution of the popen line, and never getting to the fprintf lines, but I thought that with popen mode set to "w" you could just treat the returned stream like user input, so I'm pretty confused.

share|improve this question
Have you tried flushing after calling fprintf? –  Skurmedel Feb 9 '11 at 18:48
The shell script should have EOF as the last line as a closing delimiter for the first EOF. It will work without it, but it may give a warning. You would definitely need it if there were more commands in the script following those data lines. –  Dennis Williamson Feb 9 '11 at 19:30

2 Answers 2

up vote 2 down vote accepted

You probably need to add some newlines (\n) to the end of those fprintf strings...

share|improve this answer
Wow. Never would have thought of that, but so simple. It works now. Thanks! –  tel Feb 9 '11 at 18:51
And you don't need the EOF. "<<EOF" is a bash construct that means "feed every line in this script until a line with just EOF on it to the process you're starting". You implemented the same thing with popen("w"). –  Arkadiy Feb 9 '11 at 19:17

have you checked the value of pdb2gmx - do you have the path set correctly so that your program finds the pdb2gmx executable?

You might also want to call fflush() after the fprintf()

share|improve this answer

Your Answer


