1

The Java program has to launch few prorams that are launched using a command promt(one of them is nginx). How could I handle and send commands to the program from my Java application?

I found this library http://commons.apache.org/proper/commons-cli/usage.html But I'm not sure how it helps..

I do NOT need code. I need an explanation on how things like these work.

1
  • 1
    I think what you want is Runtime.exec. Here's a question that's trying what I think you're doing, and some good starting code: stackoverflow.com/questions/9548232/… Commented Jun 26, 2014 at 16:53

3 Answers 3

3

Well keep in mind its never a nice solution.

You act like you would be on a command line so you execute Commands like you would on the shell. And does always depend on your platform.

You said you don't want code, I will give it to you anyway ;)

Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("service nginx start");

That is done with plan java.

I highly advise you to use a script language for that. Thats just not Java.

Sign up to request clarification or add additional context in comments.

2 Comments

Hm it seems much easier than I thought... for now. The rason why I use Java is that the program should start several programs and also be cross-platform. Ofcourse it will actually just run different programs for different OS.... But the user shouldn't know that!
Use python. Thats the best you can do.
2

additional info:

One thing to remember is to use the streams on process to send input and check output (from Process class)

abstract InputStream    getErrorStream()
Returns the input stream connected to the error output of the subprocess.

abstract InputStream    getInputStream()
Returns the input stream connected to the normal output of the subprocess.

abstract OutputStream   getOutputStream()
Returns the output stream connected to the normal input of the subprocess.

2 Comments

Is there some one stream for all of them? Because I think I should handle or atleast look at all of their data
Not quite sure what your asking. basically your grabbing the std in/out/error for the process.
1

If you need to execute shell commands, this can be achieved like so (This example uses bash as the executing process)

Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","my_script.sh"});

You'll have to write your own script for this, but you don't even have to put it in a file. If you wanted to give user-like input to a command, keep in mind that you can pipe in the result of an echo to a command and it will act as a user typing that command. e.g

echo 1234 | pinTaker.sh; 

This will effectively "type in" 1234 to the pinTaker script. This can also be used for things like typing in a password for ssh (Though this is not a good idea, it's a good example..)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.