3

我想使用 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.
4

1 回答 1

1

问题是您正在尝试执行此操作:su -c "rsync -avrco --progress /opt/tmp /opt/tmp2" apache使用双引号为su分隔一个参数,但是 shell 可以理解双引号,而不是 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 = new String[] {"su", "-c", "rsync -avrco --progress /opt/tmp /opt/tmp2", "apache"};
        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());
    }

}
于 2013-07-19T12:17:17.480 回答