Adam
Adam

Reputation: 299

How do I get the return code in Java after executing a windows command line command

I'm doing something like this in Java right now

Process p = Runtime.getRuntime().exec("ping -n 1 -w 100 127.0.0.1")

How can I read the windows exec code? I already know how to read the command line output from the command, but what if I just want the 0 or 1 telling me whether it was successful or failed?

Upvotes: 8

Views: 11518

Answers (4)

hmjd
hmjd

Reputation: 121971

Use Process.exitValue() method. You will need to handle the exception thrown if the process has not yet exited and retry.

Or, you could use Process.waitFor() to wait for the process to end and it will return the process exit value also (thanks to increment1).

Upvotes: 8

Sam Goldberg
Sam Goldberg

Reputation: 6801

next line of code:

int returnCode = p.waitFor();

This blocks until process is complete. You can also use the Process.exitValue() method, if you don't want to block. See Java6 Process class API doc

Upvotes: 5

Olaf
Olaf

Reputation: 6289

You

waitFor()
it and then get
exitValue()
.

Upvotes: 0

Nate W.
Nate W.

Reputation: 9249

You can use Process#exitValue()

Upvotes: 2

Related Questions