using cmd with in responsive mode in c++ or java

c++, cmd, exec, java, openssl

Solution

Easy enough in Java. Just:

- Get the Process handle.

- Read the Process' input stream for prompts written to stdout.

- Respond to prompts by writing to the Process' output stream.

Here's a quick Groovy sample because it's even easier than Java:

def cmd = ... // the command you want to run
def process = cmd.execute()
def processStdout = new Scanner(process.inputStream)
def processStdin = process.outputStream
def outputLine = processStdout.nextLine()
if (outputLine == 'some prompt written to stdout') {
    processStdin << 'your response\n'
}

If you can't follow the Groovy, I can expand it to Java.

Note that this sample doesn't handle the potentially important tasks of ensuring the stdout and stderr of the nested process are fully consumed to prevent blocking, nor does it handle ensuring the process exits cleanly.

Update: Here's that same thing in Java:

import java.io.OutputStream;
import java.util.Scanner;

public class SubprocessIO {
    public static void main(String[] args) throws Exception {
        String[] cmd = { ... your command as a series of strings ... };
        Process process = Runtime.getRuntime().exec(cmd);
        Scanner processStdout = new Scanner(process.getInputStream());
        OutputStream processStdin = process.getOutputStream();
        String outputLine = processStdout.nextLine();
        if (outputLine.equals("some prompt written to stdout")) {
            processStdin.write("your response\n".getBytes());
            processStdin.flush();
        }
    }
}

I forgot to make a note on the first go-round that the `\n` in the response is crucial, assuming the app is expecting you to enter something and then press Enter. Also, you're probably better off using the `line.separator` system property

Problem

I am using OpenSSL in my c++ app, The problem is if I use `exec("Open ssl command")` Then it will execute that particular command , but actually this command is repsonsive,I mean it further asks you `"Are you sure you want to do this Y/N?"` I don't know how to cater this scenario.How can I use java or C++ to run a command line which is responsive,Any help would be appreciated. Thanks

Original source

Related problems