我想使用 rsync 来备份文件。我像这样使用Java调用shell
String cmd = "su -c \"rsync -avrco --progress /opt/tmp /opt/tmp2\" apache";
Process p = Runtime.getRuntime().exec(cmd);
但是 p.waitFor()|p.exitValue() 是 125。为什么是 125 ?
当cmd为“su -c whoami”时,p.waitFor()|p.exitValue()为0。没关系!
完整的java测试代码是:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws Exception {
String cmd = "su -c \"rsync -avrco --progress /opt/tmp /opt/tmp2\" apache";
// String cmd = "su -c whoami";
Process p = Runtime.getRuntime().exec(cmd);
BufferedInputStream inputStream = new BufferedInputStream(p.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
inputStream.close();
reader.close();
System.out.println(p.waitFor());
System.out.println(p.exitValue());
}
}
顺便说一句,我有临时方法:
1.write cmd to file
2.use Runtime.getRuntime().exec("sh file");
it works well.