【问题标题】:Java Process getting stopped when run in background in linuxJava进程在linux后台运行时停止
【发布时间】:2018-08-20 21:44:29
【问题描述】:

我有下面的代码行`

private String build(String command) {
        ShellExecutable obj = new ShellExecutable();
        String output = obj.executeCommand(command);
        return output;
    }

    private String executeCommand(String command) {
        StringBuffer output = new StringBuffer();
        Process p;
        String[] cmdarray = { "bash", "-c", command };
        try {
            System.out.println("Before Command Execution in Bash..& command is: " + command);
            p = Runtime.getRuntime().exec(cmdarray);
            System.out.println("After Command execution in Bash & Before waitFor..");
            p.waitFor();
            System.out.println("After wait for:  " + p.exitValue());
            System.out.println("After wait for:  " + p.isAlive());
            System.out.println("After Command execution in Bash..");
            if (p.getInputStream() != null) {
                System.out.println("Input Stream is present");
                BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line = "";
                while ((line = reader.readLine()) != null) {
                    output.append(line + "\n");
                }
            }

            if (p.getErrorStream() != null) {
                System.out.println("Error Stream is present");
                BufferedReader errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                String errorLine = "";
                while ((errorLine = errorReader.readLine()) != null) {
                    output.append(errorLine + "\n");
                }
            }
        } catch (Exception e) {
            System.out.println("Exception Occured:" + e.getLocalizedMessage() + "Message is:" + e.getMessage());
        }
        return output.toString();
    }

`

我正在尝试在 Linux 中将其作为前台进程运行,它运行良好。但是,当我尝试使用 nohup 运行与后台进程相同的进程时,服务正在停止。我在堆栈溢出方面发现了类似的问题,但我无法找出这种特殊情况的解决方案。

对于上面的代码,我得到的输出如下:

调用 listApps...

在 Bash 中执行命令之前..& 命令是:xxxxxxxx

在 Bash 中执行命令之后 & 在 waitFor 之前..

[1]+ 停止 nohup java -jar ReadingShell-0.0.1-SNAPSHOT-jar-with-dependencies.jar

我在上面的代码中没有遇到任何异常,它只是停止而不显示任何内容。但是,当我尝试在 p.waitFor() 之前显示 p.exitValue() 时,我打印了堆栈跟踪,如下所示,

java.lang.IllegalThreadStateException: process hasn't exited
at java.lang.UNIXProcess.exitValue(UNIXProcess.java:424)
at org.monitoring.ReadingShell.ShellExecutable.executeCommand(ShellExecutable.java:101)
at org.monitoring.ReadingShell.ShellExecutable.build(ShellExecutable.java:82)
at org.monitoring.ReadingShell.ShellExecutable.getApplicationList(ShellExecutable.java:46)
at spark.RouteImpl$1.handle(RouteImpl.java:72)
at spark.http.matching.Routes.execute(Routes.java:61)
at spark.http.matching.MatcherFilter.doFilter(MatcherFilter.java:130)
at spark.embeddedserver.jetty.JettyHandler.doHandle(JettyHandler.java:50)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1568)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at org.eclipse.jetty.server.Server.handle(Server.java:564)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:317)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:279)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:110)
at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:124)
at org.eclipse.jetty.util.thread.Invocable.invokePreferred(Invocable.java:128)
at org.eclipse.jetty.util.thread.Invocable$InvocableExecutor.invoke(Invocable.java:222)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:294)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.produce(EatWhatYouKill.java:126)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:672)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:590)
at java.lang.Thread.run(Thread.java:745)

【问题讨论】:

  • 也打印 p 的值,将整个东西包装在 try catch 中并转储异常
  • 我试过了,异常是:异常发生:进程没有退出
  • 在您的问题中提供堆栈跟踪
  • Marged,你这是什么意思?我向您提供了当我尝试访问 p 的退出值而不调用 p.waitFor(); 时遇到的异常;
  • 异常有名称和堆栈跟踪,您提供的内容不完整。从一开始就值得一提的是堆栈跟踪和错误

标签: java linux process


【解决方案1】:

您必须在等待子进程结束之前读取输出流。否则,如果孩子向其中一个流写入超过缓冲区的价值(512B?4K?),它将等待直到有东西读取并清空缓冲区。但这不会发生,因为您的父进程已经在执行waitFor()

因此,您必须创建两个线程来读取这些输出流,并在调用waitFor() 之前启动它们。

【讨论】:

  • 我会说这是真正的问题
【解决方案2】:

通过阅读 opendjk source code for UnixProcess 我们看到以下内容

public synchronized int waitFor() throws InterruptedException {
    while (!hasExited) {
        wait();
    }
    return exitcode;
}

public synchronized int exitValue() {
    if (!hasExited) {
        throw new IllegalThreadStateException("process hasn't exited");
    }
    return exitcode;
}

hasExited 永远不会在文件中重置,因此从逻辑上讲,exitValue() 在调用 waitFor() 后无法抛出。 (除非被打断)

运行时的某些内容必须与问题的代码不同。显示问题的最小完整示例类以便我们重现它会有所帮助。

【讨论】:

  • 不,它与上面的代码相同。删除所有打印语句并在前台运行它,然后使用 nohup 运行它。它失败了。
  • @Cheater 你能用一个完整的类来更新你的问题,用最少的代码重现错误吗?
  • 很抱歉,我无法更新整个班级。但是,我分享的代码与shell进程有关。您需要做的就是将 shell 命令传递给 build 方法。
  • @Cheater 正如您从我上面的代码中看到的那样,如果您在前一行调用 waitFor(),exitValue() 不可能抛出 IllegalThreadStateException。您的问题缺少某些内容
【解决方案3】:

我遇到了类似的问题。如果在前台运行 jar 文件会很好,但在 nohup 中执行时停止,进程/作业进入停止状态。

发现如果任何内部脚本尝试从终端读取,nohup 将进入停止状态 - 请参阅帖子 here

按照this 线程的建议,我使用 tmux 解决了这个问题

【讨论】:

    最近更新 更多