Java调用bash“su -c ... username”退出代码125

时间:2013-07-19 06:10:08

标签: java runtime exec su

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

1 个答案:

答案 0 :(得分: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());
    }

}