简体   繁体   English

使用ProcessBuilder将错误重定向到文件

[英]Redirection of error into a file using ProcessBuilder

I am trying to redirect error messages produced by GCC compiler into a file during the compilation of a C program using ProcessBuilder. 我试图在使用ProcessBuilder编译C程序期间将GCC编译器产生的错误消息重定向到文件中。 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? 有人可以建议这样做的方法吗?

Command-line redirection is a feature provided by the shell that you're using (bash, sh, csh, etc). 命令行重定向是您所使用的Shell(bash,sh,csh等)提供的功能。 Your ProcessBuilder is launching gcc directly, without using a shell. 您的ProcessBuilder无需使用外壳程序即可直接启动gcc 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. 首先,Java 7版本的ProcessBuilder添加了一些功能来重定向子进程的标准I / O通道。 If you're using Java 7, this should work: 如果您使用的是Java 7,这应该可以工作:

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. 如果您不使用Java 7或不使用wnat来执行此操作,则可以运行shell并使其运行gcc。 This method gives you full access to the shell's command-line parsing features: 此方法使您可以完全访问Shell的命令行解析功能:

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. 在这种情况下,最后一个参数可以是您可以在sh命令行中键入的任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM