Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1047345
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T16:17:09+00:00 2026-05-16T16:17:09+00:00

I have the following code example below. Whereby you can enter a command to

  • 0

I have the following code example below. Whereby you can enter a command to the bash shell i.e. echo test and have the result echo’d back. However, after the first read. Other output streams don’t work?

Why is this or am I doing something wrong? My end goal is to created a Threaded scheduled task that executes a command periodically to /bash so the OutputStream and InputStream would have to work in tandem and not stop working. I have also been experiencing the error java.io.IOException: Broken pipe any ideas?

Thanks.

String line;
Scanner scan = new Scanner(System.in);

Process process = Runtime.getRuntime ().exec ("/bin/bash");
OutputStream stdin = process.getOutputStream ();
InputStream stderr = process.getErrorStream ();
InputStream stdout = process.getInputStream ();

BufferedReader reader = new BufferedReader (new InputStreamReader(stdout));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));

String input = scan.nextLine();
input += "\n";
writer.write(input);
writer.flush();

input = scan.nextLine();
input += "\n";
writer.write(input);
writer.flush();

while ((line = reader.readLine ()) != null) {
System.out.println ("Stdout: " + line);
}

input = scan.nextLine();
input += "\n";
writer.write(input);
writer.close();

while ((line = reader.readLine ()) != null) {
System.out.println ("Stdout: " + line);
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T16:17:10+00:00Added an answer on May 16, 2026 at 4:17 pm

    Firstly, I would recommend replacing the line

    Process process = Runtime.getRuntime ().exec ("/bin/bash");
    

    with the lines

    ProcessBuilder builder = new ProcessBuilder("/bin/bash");
    builder.redirectErrorStream(true);
    Process process = builder.start();
    

    ProcessBuilder is new in Java 5 and makes running external processes easier. In my opinion, its most significant improvement over Runtime.getRuntime().exec() is that it allows you to redirect the standard error of the child process into its standard output. This means you only have one InputStream to read from. Before this, you needed to have two separate Threads, one reading from stdout and one reading from stderr, to avoid the standard error buffer filling while the standard output buffer was empty (causing the child process to hang), or vice versa.

    Next, the loops (of which you have two)

    while ((line = reader.readLine ()) != null) {
        System.out.println ("Stdout: " + line);
    }
    

    only exit when the reader, which reads from the process’s standard output, returns end-of-file. This only happens when the bash process exits. It will not return end-of-file if there happens at present to be no more output from the process. Instead, it will wait for the next line of output from the process and not return until it has this next line.

    Since you’re sending two lines of input to the process before reaching this loop, the first of these two loops will hang if the process hasn’t exited after these two lines of input. It will sit there waiting for another line to be read, but there will never be another line for it to read.

    I compiled your source code (I’m on Windows at the moment, so I replaced /bin/bash with cmd.exe, but the principles should be the same), and I found that:

    • after typing in two lines, the output from the first two commands appears, but then the program hangs,
    • if I type in, say, echo test, and then exit, the program makes it out of the first loop since the cmd.exe process has exited. The program then asks for another line of input (which gets ignored), skips straight over the second loop since the child process has already exited, and then exits itself.
    • if I type in exit and then echo test, I get an IOException complaining about a pipe being closed. This is to be expected – the first line of input caused the process to exit, and there’s nowhere to send the second line.

    I have seen a trick that does something similar to what you seem to want, in a program I used to work on. This program kept around a number of shells, ran commands in them and read the output from these commands. The trick used was to always write out a ‘magic’ line that marks the end of the shell command’s output, and use that to determine when the output from the command sent to the shell had finished.

    I took your code and I replaced everything after the line that assigns to writer with the following loop:

    while (scan.hasNext()) {
        String input = scan.nextLine();
        if (input.trim().equals("exit")) {
            // Putting 'exit' amongst the echo --EOF--s below doesn't work.
            writer.write("exit\n");
        } else {
            writer.write("((" + input + ") && echo --EOF--) || echo --EOF--\n");
        }
        writer.flush();
    
        line = reader.readLine();
        while (line != null && ! line.trim().equals("--EOF--")) {
            System.out.println ("Stdout: " + line);
            line = reader.readLine();
        }
        if (line == null) {
            break;
        }
    }
    

    After doing this, I could reliably run a few commands and have the output from each come back to me individually.

    The two echo --EOF-- commands in the line sent to the shell are there to ensure that output from the command is terminated with --EOF-- even in the result of an error from the command.

    Of course, this approach has its limitations. These limitations include:

    • if I enter a command that waits for user input (e.g. another shell), the program appears to hang,
    • it assumes that each process run by the shell ends its output with a newline,
    • it gets a bit confused if the command being run by the shell happens to write out a line --EOF--.
    • bash reports a syntax error and exits if you enter some text with an unmatched ).

    These points might not matter to you if whatever it is you’re thinking of running as a scheduled task is going to be restricted to a command or a small set of commands which will never behave in such pathological ways.

    EDIT: improve exit handling and other minor changes following running this on Linux.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following code example (see below). My problem is that the tooltip
I have the following example code: $dataProvider = new CActiveDataProvider('firstTable', array('criteria' => array( 'select'
Say I have the following code: <div onclick='location.href=http://www.example.com/'> <a href='#' onclick='alert(blah)'>click</a> </div> Is there
On a report I have the following code for a field: =Sum([PartQty]*[ModuleQty]) Example results
Say suppose I have the following Java code. public class Example { public static
I have the following code below on my website. It's used to find the
I have the following code to perform validation of SubmitForm shown below on click
I have the following code (note the code below doesnt update the property) private
I have the following C Header/Code Example: Header file struct category_info { int id;
I have the following code (just as a test) and I want to create

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.