Domanda

I am trying to redirect error messages produced by GCC compiler into a file during the compilation of a C program using ProcessBuilder. Code is like this

ProcessBuilder processBuilder1 = new ProcessBuilder("/usr/bin/gcc",
"-o"+"/home/hipad/hipad/UserProject/example","/home/hipad/hipad/UserProject/example.c
2>/home/hipad/hipad/UserProject/example.gccmessages");

processBuilder1.start();

But this is giving error.The error is

"/usr/bin/gcc,-o/home/hipad/hipad/UserProject/example,/home/hipad/hipad/UserProj‌​ect/example.c 2>/home/hipad/hipad/UserProject/example.gccmessages": error=2, No such file or directory

Can anybody suggest the way to do it?

È stato utile?

Soluzione

Command-line redirection is a feature provided by the shell that you're using (bash, sh, csh, etc). Your ProcessBuilder is launching gcc directly, without using a shell. So shell features like redirection and piping aren't available.

There are two solutions. First of all, The Java 7 version of ProcessBuilder adds functions to redirect the standard I/O channels for the child processes. If you're using Java 7, this should work:

ProcessBuilder pb1 = new ProcessBuilder(
    "/usr/bin/gcc",
    "-o",
    "/home/hipad/hipad/UserProject/example",
    "/home/hipad/hipad/UserProject/example.c");
pb1.redirectError(new File("/home/hipad/hipad/UserProject/example.gccmessages"));

If you're not using Java 7 or don't wnat to do this, you can run a shell and have it run gcc for you. This method gives you full access to the shell's command-line parsing features:

ProcessBuilder pb1 = new ProcessBuilder(
    "sh",
    "-c",
    "gcc -o /home/hipad/hipad/UserProject/example /home/hipad/hipad/UserProject/example.c 2> /home/hipad/hipad/UserProject/example.gccmessages");

In this case, the final argument could be anything you can type at an sh command line.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top