4

这是我要运行的命令:

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

备份 postgres 数据库。

如果我现在在 linux shell 中,作为 root,它工作得很好。

但是现在,我想从 java 应用程序中运行它,如下所示:

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

它抛出一个错误:

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

现在我将代码更改为:

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

我现在该怎么办?

4

2 回答 2

3
exec(new String[]{"sh", "-c", "su - postgres ..."});
于 2010-12-30T17:19:47.667 回答
3

除了上面给出的答案(理解你的问题很好)之外,记住你总是可以通过把你的命令放在一个 shell 脚本文件中来让你的生活更轻松。例如,一个dumppg.sh只包含两行的文件:

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

只需使其可执行,并(在测试后)从 java 调用它。

于 2010-12-30T17:31:44.207 回答