如何在 Java 中捕获 shell 命令的退出状态?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12892665/
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
How to capture the exit status of a shell command in Java?
提问by Niranjan Subramanian
I'm creating a Junit test file for my CSVreader. I'm reading the contents of CSV files and writing the contents into another file. I want to compare them using diff utility and I want to use the exit status of diff to know whether the contents are same or not. Generally $? gives the exit status but I don't know how to capture it and use it in my code. Can anyone help me in this regard?
我正在为我的 CSVreader 创建一个 Junit 测试文件。我正在读取 CSV 文件的内容并将内容写入另一个文件。我想使用 diff 实用程序比较它们,我想使用 diff 的退出状态来知道内容是否相同。一般$? 给出退出状态,但我不知道如何捕获它并在我的代码中使用它。任何人都可以在这方面帮助我吗?
This is how my code looks
这是我的代码的样子
boolean hasSameContents = false;
command="diff "+mp.get("directory")+"/"+fileName+" "+mp.get("outdir")+"/"+fileName;
p= Runtime.getRuntime().exec(command);
p.waitFor();
After this I want to get the exit status and use it in a if condition like this
在此之后,我想获得退出状态并在这样的 if 条件下使用它
if(exit_status==0)
hasSameContents = true;
else
hasSameContents = false;
Even alternative suggestions appreciated. :)
甚至替代建议表示赞赏。:)
回答by MadProgrammer
You're looking for Process#exitValue
您正在寻找Process#exitValue
String command = "diff "+mp.get("directory")+"/"+fileName+" "+mp.get("outdir")+"/"+fileName;
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
int exitStatus = p.exitValue();
Don't forget, you should read the contents of the InputStream
even if you don't care, some processes will choke (not finish) until the output buffer has been read...
不要忘记,InputStream
即使您不在乎,也应该阅读内容,某些进程会阻塞(未完成),直到读取了输出缓冲区...
回答by Aditya Jain
You can try using ProcessBuilder
class to create a Process
object, whose exitValue()
should help you.
您可以尝试使用ProcessBuilder
类来创建一个Process
对象,它exitValue()
应该可以帮助您。
回答by Daniel Pryden
回答by logoff
Use method waitFor() of class Process. It returns an int, the return value of the process.
使用类 Process 的方法waitFor()。它返回一个 int,即进程的返回值。