bash 此脚本可以等待外部进程完成吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4503240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:08:40  来源:igfitidea点击:

Can this script wait for an external process to complete?

bashshellwait

提问by Chris

I have written this shell script as wrapper to a JAR file. The script launches the JAR without problem but completes without waiting for the JAR to finish its job.

我已将此 shell 脚本作为 JAR 文件的包装器编写。该脚本可以毫无问题地启动 JAR,但无需等待 JAR 完成其工作即可完成。

#!/bin/bash

export WORK=/opt/conversion
export LOG=$WORK
export [email protected]
export JAVA_BASE=/usr/java/jdk1.6.0_06
export JAVA_HOME=/usr/java/jdk1.6.0_06/bin
export JAR=$WORK/conversion.jar
export CLASSPATH=$JAVA_BASE/lib/tools.jar
export CLASSPATH=$CLASSPATH:$WORK/lib/ojdbc14.jar
export CLASSPATH=$CLASSPATH:$JAR

$JAVA_HOME/java -Xms256M -Xmx512M -classpath $CLASSPATH com.myapp.cam.conversion >>$WORK/job.out 2>&1 &

echo $! > $WORK/job.pid
mail -s "Conversion" $XMAIL < $WORK/user_message
exit 0

Is there a way to have the script wait on my JAR file to complete?

有没有办法让脚本等待我的 JAR 文件完成?

Thanks for your input.

感谢您的输入。

回答by Blagovest Buyukliev

As others have said, remove the &and bash will wait till the command finishes. If you insist on running your process in the background, here is what you could do:

正如其他人所说,删除&bash 将等到命令完成。如果您坚持在后台运行您的进程,您可以执行以下操作:

pid=`pidof java`

if [ "$pid" ]; then
    while kill -0 "$pid"; do
        sleep 1
    done
fi

The killcommand is normally used to send signals to a particular process, but by using 0as a signal you are only checking whether a process with such a pid exists without sending a signal.

kill命令通常用于向特定进程发送信号,但通过0用作信号,您仅检查是否存在具有此类 pid 的进程而不发送信号。

回答by codaddict

You have a &at the end of the command:

&在命令末尾有一个:

$JAVA_HOME/java -Xms256M -Xmx512M -classpath $CLASSPATH com.myapp.cam.conversion >>$WORK/job.out 2>&1 &

which makes it run in background.

这使它在后台运行。

Remove the &to wait for the javaprocess to complete before you proceed in the script.

删除&以等待java进程完成,然后再继续执行脚本。

回答by Paused until further notice.

If you want to run it in the background, add a waitcommand at the end of the script.

如果要在后台运行它wait,请在脚本末尾添加一个命令。

回答by wilhelmtell

Don't run the conversion Java application in the background. Or, run psrepeatedly until you don't see the pid. This will allow you to do stuff while waiting.

不要在后台运行转换 Java 应用程序。或者,ps重复运行直到看不到 pid。这将允许您在等待时做一些事情。