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,
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.
Are you waiting for process A to finish before running process B?
"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.
Related
Well I know it is a stupid question, but lets think on it for a second.
Why can't we have a repl mode or kind of a shell for Java. Say I just want to do Math.max(2,3) to get output 3. It can be similar to Scala repl mode, where by default the class and main declarations are handled (it extends to App) and only an expression is evaluated.
Technically:
There is an interpreter running behind can execute it - If scala and groovy can, then that means the JVM is not the major issue
If javac is the reason, say we remove all optimizations and it directly converts line by line strictly to java byte code, then there should be a way out. Type Inference might not be strong to show a lot of information, but atleast the output of methods can be shown. Probably javac can be a bit modified for such cases
Ex: In the debugger, we attach break points to the line and then execute forward. A similar strategy can be applied
It would be cool to have a default shell for each JVM process, where on the run, one can access or set some say static variables and have live information.
All this would have been thought off, but why hasn't it been accepted by majority (there are some open source implementations though)
This is more or less exactly what BeanShell does.
The Display view in Eclipse provides a lot of convenient behaviour in this area, with command completion, access to the running application stack, and console output through System.out.
Like #Sean suggested you can indeed use bean shell in repl mode.
java -cp ./bsh-2.0b4.jar bsh.Interpreter
BeanShell 2.0b4 - by Pat Niemeyer (pat#pat.net)
bsh % System.out.println("Hello World");
Hello World
Alternatively, the less known Display tab on the eclipse IDE can execute arbitrary java code and evaluate expressions on the fly. Ctrl+U runs the expression and Ctrl+Shift+I evaluates them. It is not repl mode, but comes close.
You could try http://www.javarepl.com/ or console version from https://github.com/albertlatacz/java-repl
I have a piece of Java code and I compiled and ran it. I got an output and I made some changes to it, before compiling and running again.
Is there any difference between the time it takes during the first compilation compared to the second compilation. Similarly are there changes between the first runtime to second runtime? Is there any way to find that difference in processing time?
There can be certain difference according to the changes you have made.
It depends on what your program did and what it does now, i think you can understand that.
To check the time, you can do this by creating a thread that can act like a timer just after the program execution, and stop that thread after all your processes have been done and simply display to see the time.
Firstly, I'm unsure why this is important to you. Perhaps by providing some more context you will get a more detailed answer.
Comparing compilation time can be achieved using Operating System tools. For example, on Linux try using time.
Complete execution time of your two Java programs can be achieved in the same fashion. However, if you are looking more closely at whether your code changes have improved your execution performance, I would suggest you Google "benchmarking in Java" to find a wealth of information on the correct methods to benchmark code.
If you use Eclipse you can configure Project -> Build Automatically to rebuild the project after every change.
So once you want to run it would take minimal time.
Here's my issue. I have an existing .jar file that I must use in my program. The program, however, is written in Python.
Since my program is taking a long time to run (a named entity tagger on a large development corpus) I profiled it using cProfiler and lined profiled it using line_profiler. It seems that 92% of the time is spent on this task.
I am currently using the following code:
import subprocess as sub
sub.call(["java", "-jar", "-Xmx512m", "MyFile.jar",
featuresFileName, numIterations, featureCutOff])
I read somewhere about subprocess vs Popen and other bits and pieces, but couldn't find a good solution that does not require subprocess or os calls (of course, there may not be any).
I'd really appreciate some advice on the fastest way to run a .jar file from within a Python script. Note, however, that I cannot modify the Java code nor do I have access to speak to the developer of that code.
Alternatively, and I don't know if this will help or if I'm simply grasping at straws here, but perhaps there is a way to keep the process called in sub.call() above in the background, somehow keeping the JVM running (?) so that I can simply invoke the jar file. Maybe that can help reduce startup costs? BTW I am a total Java newbie (mostly C++,C#,Python experience) so my question could make no sense whatsoever - I apologize in advance...
You could try porting your Python to Jython, and then run it all natively in the same JVM (that may or may not work). That way you have effectively zero start up time, and the JVM has enough time to leverage its JIT over time to ideally give you better performance overall.
That indicates that most of the time is spent in this process. It may not be the startup time which is the problem. It may be what it does once it has started.
The only way around this I can think of is to run the process in the background, multiple time concurrently if that is an option. (concurrently rather than running one after another)
Try with "-client" option. It should reduce JVM startup time.
By analysing the manifest file of the jar file you can find out the class name of the jar file which is used. So then you could in principle write your own small java daemon which is listening for new arguments to arrive and calls the main() function of the appropriate class. But it is really worth the effort only if startup costs are the issue.
A project I am currently involved in uses JavaCv/OpenCv for face detection. Since the OpenCv occasionally throws an error, and the propagation of OpenCv/C++ errors to Java Exceptions isn't fully functional yet, this means the Java main-loop crashes with no way to recover.
However, the code gives mostly accurate results, and since we're running it on a large database I baked a quick Batch-script around the execution to keep it going, and the Java code internally manages an id, to make sure it continues from just after where it crashed.
:RETRY
java -Xmx1024m -jar Main.jar
IF ERRORLEVEL 1 GOTO RETRY
EXIT 0
However, occasionally I get a Runtime Error pop-up, as follows:
Microsoft Visual C++ Runtime Library
Runtime Error!
Program: C:\Windows\System32\java.exe
This application has requested the runtime to end in an unusual way.
Please contact the application's support team for more information.
At which point the code execution halts until the pop-up is clicked, which is really annoying, as it means my code can't run without me babysitting it.
I found this question, which basically asks the same thing. There is an accepted solution for that question, but since I'm not directly working with C++, I don't see how I can implement this.
Is there a Batch-level solution to this problem? Is there a Java/JavaCv-level solution to catch the C++ errors coming from OpenCv? Any other solution?
Interesting question.
Java.exe is dependent on one or more of Visual C++ DLLs (like MSVCRT.DLL, msvcr90.dll etc). Probably the JAR file is causing Java.exe to cause this error. Java.exe must be calling some CRT function which is raising the exception and hence the Runtime Error.
The best bet you can do is to launch the process, let this error pop and then start Process Explorer, and see the call stack. Nevertheless, solving this issue is most probably out of your control. May be latest version of Java may help.
I'm modifying a rather big codebase and I'm in the process of debugging. My code doesn't terminate, so I don't get a stacktrace. I tried to isolate the trouble code with breakpoints, but unfortunately it runs through sections that are executed all the time (transaction manager), so I'm clicking to death. Furtermore, i get the impression that the code breaks only under certain conditions, but runs fine most of the time.
Is there a way in Intellij to see the last method that was / the current method that is executed?
thanks
You can use BTrace, a tracing tool, to print out the name of every method entered in your program. There is a sample script that comes with BTrace, called AllMethods, which does just that.
All of you have to do is start your java process and then run the BTrace script against the JVM's PID. It will print out every method entered. You can restrict it to certain packages if you like. For more information about using BTrace check out this tutorial.
Use a profiler. It will give you a breakdown of which methods are executing, how much time your program spends in each method etc etc. It should be quite easy to find out from there where your program is spending its time.
JProfiler is an example. I think it has a trial / demo version which is fully functional.