Reputation: 41
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.
Upvotes: 3
Views: 2033
Reputation: 17422
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());
}
}
Upvotes: 1