0

Here is the code:

String cmd = "/usr/local/postgresql/bin/postgres -D /usr/local/postgresql/data >logfile 2>&1 &";
Process p = Runtime.getRuntime().exec(cmd);

It doesn't work. The command is supposed to start the postgres server, but I checked that the server didn't start which means the command wasn't executed. But it worked if the command is like this: /usr/local/postgresql/bin/postgres -D /usr/local/postgresql/data which just start the server but no need to write to logfile.

So I guess the characters in the command maybe a problem. And I tried this solution. It still didn't work though. Then I realized maybe it's the permission issue? I mean the java file doesn't have the permission to write to the logfile? But I don't know how to solve this one. Any suggestion? Thanks in advance.

Community
  • 1
  • 1
zli89
  • 143
  • 2
  • 6

3 Answers3

0

In C#, we're able to get a handle to the console and error streams and then do with them what we please.

Instead of "> logfile ...", could you get a handle to the output streams from p and then write to your log file programmatically?

Same for the "&" at the end. Your Process API might have a method to put it in the background.

To rule out permissions, change "logfile" in your example above to something like "/tmp/mytemporarylogfile.txt" and see if that helps. (I doubt it will because I don't think it likes your shell constructs of ">", "2>&1", and "&" inside of Java. Imagine what this would do if you ran it on Windows.)

jia103
  • 1,116
  • 2
  • 13
  • 20
0

You can use the method Process.getErrorStream() to get the error stream, and with this you can its content in a file. Easier, it seems the class ProcessBuilder has a method to redirect the output to a file ProcessBuilder.redirectOutput()

However, I would't think there is a way to execute the command in background. That's make sense in a shell, but in Java?

polypiel
  • 2,321
  • 1
  • 19
  • 27
0

Redirecting to a file using the '>' operator is a function of the shell, not something inherent to the OS. You either need to spawn a shell that then runs the process, or read the output of the process and write it to the log file from Java.

brettw
  • 10,664
  • 2
  • 42
  • 59