If I am running external program(batch file) from java then, What I need to do:
if (process.exitValue() == 0) {//means executed successfully ???
Can't the return value be something else and batch executed successfully.
Is that the only way to check??
I'm a bit confused by your wording, but by convention, [exitValue()](http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html#exitValue()) returns 0 upon a successful execution. This is, as far as I know, the only way to check.
EDIT:
I suppose you could use [getErrorStream()](http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html#getErrorStream()) - I assume it'll be blank if there are no errors in the process...
Pick one from here
You could read the output stream ( or the error stream ) and interpret it
The exit code of the batch process will be defined by that process but generally an exit code of 0 is defined as successful and a non zero value indicates that something went wrong. In your batch file you can set the return code by calling:
EXIT /B %ERROR_CODE%
%ERROR_CODE% is the number that will be returned as the exit code.
On Linux, your program can return any status you want. By convention 0 means success.
For example, if you execute a shell script, the return status will be the return status of the last command executed in your script.
In many programs 0 is is success, negative numbers are errors and positive numbers are warnings. Of course this is just a convention and it all depends on what convention was followed. In most programming languages you can define an exit code for a program and that is what is picked up.
In Java System.exit(n)
In C main is defined as int main(int argc, char* argv[]) and the return from main is the return from the program.
Related
I am asking this question particularly for an Expect implementation in Java. However, I would like to know general suggestions as well.
In Expect programming, is it possible to expect exactly what is prompted after spawning a new process?
For example, instead of expecting some pattern or a fixed string, isn't it better to just expect what is prompted. I feel this should be really helpful at times(especially when there's no conditional sending).
Consider the sample java code here that uses JSch and Expect4j java libraries to do ssh and execute list of commands(ls,pwd,mkdir testdir) on the remote machine.
My question here is why is it necessary to specify a pattern for the prompt? Is it not possible it to get the exact prompt from Channel itself and expect it?
I've programmed in "expect" and in "java".
I think you misunderstand what "expect" basically does. It doesn't look for exact items prompted after spawning a new process.
An expect program basically consists of:
Something that reads the terminal
A set of patterns (typically regular expressions), coupled to a blocks of code.
So, when a new process is spawned, there's a loop that looks something like this
while (terminal.hasMoreText()) {
buffered_text += terminal.readInput();
for (Pattern pattern : patterns) {
if (pattern.matches(buffered_text)) {
String match = pattern.getMatch(buffered_text);
bufferedText.removeAllTextBefore(match);
bufferedText.removeText(match);
pattern.executeBlock();
}
}
}
Of course, this is a massive generalization. But it is close enough to illustrate that expect itself doesn't "exactly expect" anything after launching a process. The program provided to the expect interpreter (which primarily consists of patterns and blocks of code to execute when the patterns match) contains the items which the interpreter's loop will use to match the process's output.
This is why you see some pretty odd expect scripts. For example, nearly everyone "expects" "ogin:" instead of "Login:" because there's little consistency on whether the login prompt is upper or lower case.
You don't have to expect anything. You're free to just send commands immediately and indiscriminately.
It's considered good practice to only reply to specific prompts so that you don't accidentally ruin something by saying the wrong thing at the wrong time, but you're entirely free to ignore this.
The main consideration is that while your normal flow might be:
$ create-backup
$ mkdir latest
$ mv backup.tar.gz latest
With no expectations and just blindly writing input, you can end up with this:
$ create-backup
Disk full, cleanup started...
Largest file: precious-family-memories.tar (510MB)
[R]emove, [S]ave, [A]bort
Invalid input: m
Invalid input: k
Invalid input: d
Invalid input: i
Removing file...
$ latest
latest: command not found
$ mv backup.tar.gz latest
whereas a program that expects $ before continuing would just wait and eventually realize that things are not going according to plan.
A few commands are sensitive to timing (e.g. telnet), but other than that you can send commands whenever you want, with or without waiting for anything at all.
I hope to execute a bash script and obtain normal output or error message. I know for C we have erron or perror to get the number of exit code and the corresponding message. Whether or not there is an equivalent for Java. If not, how could we achieve the same task as in C?
If you start your process like this:
Process p = Runtime.getRuntime().exec("<command>");
The the error code is return like this:
int error_code = p.waitFor();
You're confusing things.
The exit status from a process, out to bash, Java or whatever environment started it, is not the same thing as the values of errno, that can be printed by perror(). The latter are errors for individual system calls, which are clearly at a much lower level.
The exit status of a process can be whatever, there's no standard for that since it's usually just pass/fail, the detailed level is typically coverered by the program itself.
See, for instance, the exit status of GNU grep:
Normally, the exit status is 0 if selected lines are found and 1 otherwise. But the exit status is 2 if an error occurred [...].
That's very high-level, and doesn't tell you what error occured inside grep, just that overall, it failed.
The method waitFor() returns an integer value which is the return code. The value 0 indicates normal termination. But what are the meanings of other return codes? I am getting an exit value 11. What does that mean? And where all the exit value codes are documented?
These values are arbitrary and up to the specific program to define. You should refer to documentation or source code of the program that is outputting this exit code.
The program return value depends on program. There is no standard for return values apart from zero meaning OK.
You have to contact author of the program or consult documentation.
Every application defines it's own exit codes. E.g. you have to look up the documentation of the application that you started using java.lang.Process. The only common thing they all have is that any other value than 0 is an error.
In the unix world on the other hand there are certain conventions, that many main stream utilities follow, but there are no guarantees.
Any value other than non-zero value indicates Abnormal termination. There is no particular rule as to what values indicate what conditions. Read the documentation for the process that you are calling.
0 --> Normal termination
!=0 --> Abnormal Termination
I have seen conversions happen of the nature that can convert intended negative error codes to convert as follows -
Error code –> -2001 -> Signed Decimal to Binary conversion -> 111111111111100000101111 -> Here 00101111 last 8 bit is picked up and converted back to Decimal – 47 !!
I am invoking a java program from a shell script "TC Shell Script" and the java program returns status codes which represent certain conditions.
The return code of the java prgram is captured in the pre-defined status variable of the TC Shell.
The return codes are captured fine.
The problem I'm facing is when the java program returns or terminates with -1 with System.exit(-1) the shell script is getting 255 as the return code.
All positive numbers are captured fine in the shell script only -1 is being read as 255.
How can i solve this.
Return codes from executables are a small positive number. Negative numbers get converted to unsigned. There is no way to get a negative number into the exit code.
This question already has answers here:
Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java
(12 answers)
Closed 7 years ago.
Can any one share to me difference between System.exit(0) and System.exit(-1) it is helpful if you explain with example.
It's just the difference in terms of the exit code of the process. So if anything was going to take action based on the exit code (where 0 is typically success, and non-zero usually indicates an error) you can control what they see.
As an example, take this tiny Java program, which uses the number of command line arguments as the exit code:
public class Test {
public static void main(String[] args) throws Exception {
System.exit(args.length);
}
}
Now running it from a bash shell, where && means "execute the second command if the first one is successful" we can have:
~ $ java Test && echo Success!
Success!
~ $ java Test boom && echo Success!
System.exit(0) means it is a normal exit from a program.But System.exit(-1) means the exit may be due to some error. Any number other that zero means abnormal exit.
The parameter of System.exit(int) is the return value of your program, which can be evaluated in batch jobs (usually for console programs). By convention, every value other than 0 inidaces that something went wrong.
If you run your Java program in Linux/Unix you can examine the result using echo $? command. This is why it is important to call System.exit(0) (this is done for you if you don't) if everything is fine and System.exit(non-zero) otherwise.