Jenkins 插件开发,ProcStarter:如何写入已运行进程的标准输入

问题描述 投票:0回答:1

我正在尝试写入已启动进程的标准输入,该进程已经在运行。 在进程启动时写入 sdtin 有效:

外部脚本1.sh:

#!/bin/sh
echo "Started at $(date)" 
read a 
echo "$(date): got '$a'"

插件中的代码:

 ProcStarter proc = launcher.launch().stderr(listener.getLogger()).stdout(listener.getLogger()).cmds("/tmp/1.sh");  
 ByteArrayInputStream res = new ByteArrayInputStream(("hellooo" + System.lineSeparator()).getBytes(StandardCharsets.UTF_8));
 proc.stdin(res).join();

在jenkins控制台中输出,开始时间的相同时间戳并写入sdtin:

$ /tmp/1.sh
Started at Thu Apr  2 10:52:02 CEST 2020
Thu Apr  2 10:52:02 CEST 2020: got 'hellooo'

我想不是在开始时间写入 sdtin,而是在 x 秒后写入,类似这样的伪代码:

  ProcStarter proc = launcher.launch().stderr(listener.getLogger()).stdout(listener.getLogger()).cmds("/tmp/1.sh");  
  proc.join(); //blocks

//somewhere in another Thread:
  Thread.sleep(15000);//pseudocode ;-)
  ByteArrayInputStream res = new ByteArrayInputStream(("hellooo" + System.lineSeparator()).getBytes(StandardCharsets.UTF_8));
  proc.stdin(res); // doesn't work

由于在 Jenkins 代理上执行,因此需要使用 hudson.Launcher.ProcStarter。 有什么想法,如何写入已运行进程的标准输入?

jenkins jenkins-plugins jenkins-agent
1个回答
0
投票

我找到了解决方案,重要的是调用 proc.writeStdin() 方法来反转 I/O 方向:

ProcStarter procStarter = launcher.launch().stderr(listener.getLogger()).stdout(listener.getLogger()).cmds("/tmp/1.sh");  
proc.writeStdin();//important ==> Indicates that the caller will directly write to the child process stdin()
Proc myProc = procStarter.start();
myProc.getStdin().write(("helloooo2" + System.lineSeparator()).getBytes(StandardCharsets.UTF_8));
            myProc.getStdin().flush();
© www.soinside.com 2019 - 2024. All rights reserved.