views:

49

answers:

4

Hi Guys

I need to compile and run a c++ program from java. I am using

Process a = Runtime.getRuntime().exec ("g++ -g function.cpp -o function"); Process b = Runtime.getRuntime().exec ("./function");

the problem is that the output I get from the c++ program is not correct but If I compile and run it myself in the command line it works just fine. The problem is Java and i dont know why.

Thanks a lot

Al,

+1  A: 

Are you waiting for process A to finish before running process B?

dark_charlie
no I dont, I am gonna try thanks.
Altober
Thanks that was it
Altober
If an answer solved your problem, please "accept" the best one by clicking the checkbox to the left.
Jim Garrison
A: 

"The output... is not correct" doesn't help anyone to diagnose your issue. You should definitely give the output you expected, and the output you saw from Java. Assuming that your program is small, you should post the source code of that too (since this is about the compilation process after all).

By the way, what happens when you navigate to the working direction of the Java program, find the function executable it generating and invoke that yourself from the command line? Is the output correct now? The answer to this will let you know whether the problem is in the compilation step or the execution step.

If it's execution, I would hazard a guess at things like the environment (envvars, PATH, etc.) but without more information it's hard to tell.

Also, as with all question that involve Processes, take a look at these common pitfalls. It looks like you're making at least one of them (the common one of not consuming output) which might lead to your program working on trivial C++ code but deadlocking on a larger codebase.

You're also not checking the output (either the return value or the stdout/stderr streams) of the compilation step at all, so you have no idea whether the compilation was successful - and if not, what (useful) error messages you got from the compiler.

Andrzej Doyle
thanks for your time. Now it is working.
Altober
+2  A: 

There is one definite and one probable problem that I see here. The definite problem is that Runtime.exec() does not wait for the process to complete. So you will need to add

a.waitFor();

before calling b.

The possible issue is that depending on how you are invoking this application, the current working directory may not be where you think it is. So function.cpp may not exist.

Dan
I Worked!!!! Thanks man!!!
Altober
A: 

Thank you all of you guy. Now its working just fine. You save me a lot of time. Problem solved!!!.

Altober