1

I'm making a terminal app and using the following code

    try {
        process = runtime.exec(command);
        BufferedReader stream = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = stream.readLine()) != null) {
            stringBuilder.append(line);
            stringBuilder.append('\n');
        }
        stream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        while ((line = stream.readLine()) != null) {
            stringBuilder.append(line);
            stringBuilder.append('\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

Problem is that everytime exec() is executed, a new shell is created. (That's what I read)

Let's say I execute cd, it will change the directory, but next time I execute a command, it will execute from /.

How do I use the same shell till the app is closed?

PS: This question is not same as How to execute cmd commands via Java I am able to execute commands, no problem! I'm not trying to execute known commands by putting them in source code. I'm getting the commands from the user. Problem is I'm not able to maintain the shell environment constant.

Community
  • 1
  • 1
Xpleria
  • 5,472
  • 5
  • 52
  • 66
  • You simply have to call a program that does not exit ... If you need to combine several statements copy them into a batch and execute that batch. If it is only about support for cd then set a working directory when calling the program. – Marged Nov 08 '15 at 18:44
  • What do you mean by `call a program`? Can you elaborate or give some code in an answer? – Xpleria Nov 08 '15 at 18:57
  • Call a program = runtime.exec( "notepad.exe" ) – Marged Nov 08 '15 at 19:10
  • I've tried that. But it somehow gets stuck if you don't call `exit` – Xpleria Nov 08 '15 at 19:12
  • I think I don't get your point. Either you want to keep the process running or closed soon. Perhaps you should mention all the commands you want to execute consecutively – Marged Nov 08 '15 at 19:14
  • It's a terminal, like linux shell. The user enters a command, and then enters another. So the sequence of commands is not known. They need to be executed as and when there's an input – Xpleria Nov 08 '15 at 19:17
  • 1
    Now I understand. I would say this is a rather big project if you want to do it right. Have you checked if one of the existing projects does what you need ? Crash for example ? http://www.crashub.org – Marged Nov 08 '15 at 19:20
  • Possible duplicate of [How to execute cmd commands via Java](http://stackoverflow.com/questions/4157303/how-to-execute-cmd-commands-via-java) – Yosef Weiner Nov 08 '15 at 19:45

0 Answers0