开发者

Runtime.exec() can't run "su - postgres -c 'pg_dump ...'"

开发者 https://www.devze.com 2023-02-01 15:51 出处:网络
This is the command I want to run: su - postgres -c \"pg_dump .....\" to backup the postgres database. 开发者_如何学编程If I am now in linux shell, as a root, it works great.

This is the command I want to run:

su - postgres -c "pg_dump ....."

to backup the postgres database.

开发者_如何学编程If I am now in linux shell, as a root, it works great.

But now, I want to run it from a java application, as:

String cmd = "su - postgres -c \"pg_dump --port 5432 .....\""
Process p = Runtime.getRuntime().exec(cmd);
// read the error stream and input stream
p.waitFor();

It throws an error:

su: unknown option "--port"
please try "su --help" to get more information

Now I change the code as:

Process p = Runtime.getRuntime().exec(new String[0]{cmd});
// read the error stream and input stream
p.waitFor();

Cannot run program "su - postgres -c \"pg_dump .....\"": java.io.IOException: error=2, no that file or directory

What should I do now?


Besides the answers given above (and it's good to understand your problem) remember that you always can make your life easier by just putting your command inside a shell script file. Eg, a dumppg.sh file which just contains two lines:

#!/bin/sh
su - postgres -c "pg_dump ....."

just make it executable, and (after testing it) call it from java.


exec(new String[]{"sh", "-c", "su - postgres ..."});
0

精彩评论

暂无评论...
验证码 换一张
取 消