gpt4 book ai didi

java - 需要有关流程的帮助

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:03:49 25 4
gpt4 key购买 nike

当我启动像 process= Runtime.getRuntime().exec("gnome-terminal"); 这样的进程时,它开始执行 shell,我想停止 shell 执行并重定向我/O 从过程中,任何人都可以告诉我该怎么做吗?

我的代码是:

public void start_process()
{
try
{
process= Runtime.getRuntime().exec("bash");
pw= new PrintWriter(process.getOutputStream(),true);
br=new BufferedReader(new InputStreamReader(process.getInputStream()));
err=new BufferedReader(new InputStreamReader(process.getErrorStream()));

}
catch (Exception ioe)
{
System.out.println("IO Exception-> " + ioe);
}


}

public void execution_command()
{

if(check==2)
{
try
{
boolean flag=thread.isAlive();
if(flag==true)
thread.stop();

Thread.sleep(30);
thread = new MyReader(br,tbOutput,err,check);
thread.start();

}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage()+"1");
}
}
else
{
try
{
Thread.sleep(30);
thread = new MyReader(br,tbOutput,err,check);
thread.start();
check=2;

}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage()+"1");
}

}
}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
command=tfCmd.getText().toString().trim();

pw.println(command);

execution_command();

}

当我在文本字段中输入一些命令并按下执行按钮时,我的输出文本区域没有任何显示,我如何才能停止 shell 执行并重定向输入和输出?

最佳答案

来自Javadoc :

The ProcessBuilder.start() and Runtime.exec() methods create a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it. The class Process provides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process.

The methods that create processes may not work well for special processes on certain native platforms, such as native windowing processes, daemon processes, Win16/DOS processes on Microsoft Windows, or shell scripts. The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (getOutputStream(), getInputStream(), getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

换句话说,在将缓冲流读取器连接到 process.getInputStream() 之后正如您所做的那样,您应该阅读其所有输出以使其正常运行。

更新: here is a simple example怎么做。

关于java - 需要有关流程的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2992801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com