首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何向现有的bash进程发出多个命令?

如何向现有的bash进程发出多个命令?
EN

Stack Overflow用户
提问于 2020-03-20 16:51:03
回答 1查看 39关注 0票数 0

我正在制作一个简单的GUI界面为一个TUI我的世界服务器,我需要发出命令到该程序的基础上的GUI事件(按钮点击等)。我创建了一个进程构建器,但是如何给正在运行的程序更多的命令呢?

我正在尝试完成的一个示例是用Java打开一个命令行程序,该程序询问我的姓名。我的问题是,我该如何给这个程序起我的名字。

我已经看过许多关于类似事情的已有的Stack-exchange*帖子,但它们都不适合我。

我在linux btw上,如果这很重要的话。

代码语言:javascript
复制
public Process runCommand(String command) throws IOException {
        ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", command, "-S");

        Process process = pb.start(); // Executes the command
        return process;
    }

    public void showCommandOutput(Process process) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); 

        String line = ""; // Empty String to put the output in
        try {
            while ((line = reader.readLine()) != null) { // For every line in the shell output
                System.out.println(line); // Print the line
            }
            try {
                process.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace(); // If this goes wrong, display stack trace
            } finally {
                quitServer(0); // External function for closing program, self explanatory
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

提前谢谢你。

EN

回答 1

Stack Overflow用户

发布于 2020-03-21 04:22:03

你已经走到一半了。调用pb.start()时返回的Process对象包含与外部程序通信所需的输入流和输出流。您已经在从process.getInputStream()中读取数据,以获取进程的输出。要向其发送输入,只需将数据写入process.getOutputStream()流。

在将readLine()与bash这样的进程一起使用时,您应该小心。当bash写出命令提示符时,它不会以换行符结尾(因此您可以在同一行中输入命令)。所以你的readLine()将永远等待不会到来的换行符。您可能希望使用无缓冲读取,并检查数据中是否有任何类似提示的内容。

如果您确定您的程序将输出文本,期望得到响应,然后读取您的输入,则可以在现有循环中执行此操作。在读取检测到的每一行之后提供一个命令是一个提示符。例如:

代码语言:javascript
复制
    PrintStream commandWriter = new PrintStream(process.getOutputStream());
    while ((line = reader.read()) != null) { // For every line in the shell output
      // if I know prompts end with a certain substring
      if (line.endsWith("$> ")) {
        commandWriter.println("echo \"this is a command I sent to a process\"");
      }
      else {
        System.out.println("Received from process: " + line);
      }
    }

但是,如果您正在与之交互的程序更具交互性,那么您可能需要启动单独的线程来读取和写入输入/输出。您必须小心处理这些进程,以确保在数据可用时不断读取这些进程中的数据。如果您忘记这样做,外部程序可能会挂起,当它卡在一个满的缓冲区。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60771031

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档