0

I have a situation where i need to execute a UNIX command from a .jar. I have tried the following ( date is arbitary):

    java.lang.Runtime rt = java.lang.Runtime.getRuntime();
    java.lang.Process p = rt.exec("sudo date --set=\"Tue Aug 11 10:10:20 BST 2015\"");
    p.waitFor();
    logger.log("executed with value: " + p.exitValue());

I was just wondering if there is a way to check the exit code in this instance?

NB: I have executed a command this way namely "sudo mkdir -p /root/abcd" which does work.

Hughzi
  • 2,470
  • 1
  • 20
  • 30
  • 2
    What is the problem? exitValue does return the exit code. – Eelke Aug 10 '15 at 08:36
  • To debug the problem you might want to read and display output from the program which is passed to your java program by the streams that you can retrieve using getInputStream() and getErrorStream(). I wouldn't be surprised if sudo is asking for a password. – Eelke Aug 10 '15 at 08:43
  • @Eelke sudo does nto ask for a password, this does concern me. – Hughzi Aug 10 '15 at 08:46
  • What do you mean by "check the exit code" ? 0 value means that the process terminates correctly. Any other value means unsuccessful termination. – Jean-Baptiste Yunès Aug 10 '15 at 10:13

2 Answers2

0

I think p.waitFor()is not the function you need - have a look here for reasons: waitFor -Process. If you use p.destroy() you will get your return value.

EDIT: I found this tutorial with the a similar code i used :) Tutorial

Community
  • 1
  • 1
MrT
  • 594
  • 2
  • 17
  • `Process.destroy()` will kill the subprcess and return type is `void`. Why do you think this will give the exitvalue? – Codebender Aug 10 '15 at 08:40
  • i think this is the problem of the question. I demonstrate that the function `exitValue()` return the right value if the subprocess ends. the `destroy()`-function demonstrate that. Like you mentioned it kills the subprocess and then you got a return value. – MrT Aug 10 '15 at 08:41
  • 1
    The example is kind of valid for a windows GUI app but not for a console program. destroy tries to terminate a process quickly. For console programs this often means an interrupt signal (ctrl+c) or a kill signal. This means the command does not complete succesfully. You need to use waitfor so the process can do what it is supposed to do. – Eelke Aug 10 '15 at 08:57
  • why a downvote? I get the returnvalue and this is not depending if the process terminates well or is destroyed? There is no wrong thing in this answer. – MrT Aug 10 '15 at 09:00
  • @MrT I agree a downvote in this instance is wrong, the answer solved a problem and pointed out good sources for further information. I will upvote but this will just offset your downvote – Hughzi Aug 10 '15 at 09:01
0

p.waitFor() is sufficient, i was looking in the wrong log file... a little embarrassing but admitting these mistakes is the first step towards not repeating them. Thank you all for your help!

Hughzi
  • 2,470
  • 1
  • 20
  • 30