Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to use rsync to backup files. I use Java call shell like this

String cmd = "su -c \"rsync -avrco --progress /opt/tmp /opt/tmp2\" apache";
Process p = Runtime.getRuntime().exec(cmd);

but the p.waitFor()|p.exitValue() is 125. why 125 ?

when the cmd is "su -c whoami", the p.waitFor()|p.exitValue() is 0. it is OK!

the full java test code is:

    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());
        }

    }

by the way, i have temp way to do it:

1.write cmd to file
2.use Runtime.getRuntime().exec("sh file");
it works well.
share|improve this question

1 Answer

Problem is that you are trying to execute this: su -c "rsync -avrco --progress /opt/tmp /opt/tmp2" apache using double quotes to delimit one parameter for su, but double quotes are understood by the shell, not by Java (that's why in your second case it works).

To make it work try this:

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());
    }

}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.