Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

JavaWorld Daily Brew

How can I call a C program in a Shell scipt from java


Hi all,
I have a C program namely NetLibExample.c.I have compiled it to get a NetLibexample executable in RHEL5. It is successfully running from the terminal itself by the syntax: ./NetLibExample
I have written a shell script to call the same.The shell script is test.sh

test.sh
cd /working/AVClient
mkdir habib_test
./NetLibExample
echo "1 image captured"

This shell is running successfully and giving me the output( a new folder habib_test and output from the C program)

I have to call the shell script from Java program.The program is like this.
TestShell.java
public class TestShell {
public static void main(String[] args) {
try{
System.out.println("I am here to test the shell correctly");
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("/working/test.sh");
int exitVal = proc.waitFor();

}catch(Exception e){
e.printStackTrace();
System.out.println("Exception caught.........."+e.toString());
}
}
}

But when I am trying to call the shell from Java,shell is runnin g properly as I am getting the new folder created from the shell.The java program is giving a exception:
java.lang.IllegalThreadStateException: process hasn't exited
at java.lang.UNIXProcess.exitValue(UNIXProcess.java:172)
at TestShell.main(TestShell.java:27)
Exception caught............java.lang.IllegalThreadStateException: process hasn't exited

Please help me.Thanks in advance.

Your rating: None

May be adding an 'exit 0' at

May be adding an 'exit 0' at the end of the script may help...

Deadlock?

Your "NetLibExample" program produces output to stdout or stderr, which may be causing a deadlock because your Java code isn't reading those streams.

http://java.sun.com/javase/6/docs/api/java/lang/Process.html :
"Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock."

Follow this link for an implementation of a OutputStream sink.
http://vyvaks.wordpress.com/2006/05/27/does-runtimeexec-hangs-in-java/

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <p> <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <br /> <br> <strike>
  • Lines and paragraphs break automatically.
  • Use <!--pagebreak--> to create page breaks.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options

CAPTCHA
Just checking to see if you're an actual person rather than a spammer. Sorry for the inconvenience.