简体   繁体   English

Unix上的C ++:重定向Shell输出

[英]C++ on Unix: Redirecting Shell Output

I have a command that compiles test.cpp and is supposed to store output in the output file. 我有一个编译test.cpp的命令,应该将输出存储在输出文件中。 Here is an example of my generated cmd: 这是我生成的cmd的示例:

g++ tmp/test.cpp -o tmp/test &> tmp/compile.out g ++ tmp / test.cpp -o tmp / test&> tmp / compile.out

when I use system() , it does not work. 当我使用system()时 ,它不起作用。 Even though it creates output file, it still prints everything to the main console window. 即使创建了输出文件,它仍然将所有内容打印到主控制台窗口。 When I execute it in terminal, it works just fine. 当我在终端中执行它时,它就可以正常工作。

I also tried use popen() and fgets() (just copying the code from here ) but same happened. 我也尝试使用popen()fgets() (只是从此处复制代码),但同样发生了。 I probably could just fork my process and use freopen or something but I have sockets and multiple threads running in the background. 我可能可以分叉我的进程并使用freopen或其他东西,但是我在后台运行套接字和多个线程。 I guess they would be duplicated as well, which is not good. 我想它们也会被复制,这不好。

Any ideas why it may fail? 有什么想法可能会失败吗?

According to the man-page of system , it invokes sh which is the standard bourne shell (not bash, Bourne Again SHell). 根据system的手册页,它调用标准的bourne shell sh (不是bash,Bourne Again SHell)。 And the bourne shell doesn't understand &> . 而且bourne shell无法理解&> So you might need to use the old style: 因此,您可能需要使用旧样式:

g++ tmp/test.cpp -o tmp/test >tmp/compile.out 2>&1

I tried the following variant on popen() and it worked for me under Mac OS X 10.7.2, gcc 4.2.1: 我在popen()上尝试了以下变体,它在Mac OS X 10.7.2,gcc 4.2.1下对我有用:

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

int main (int argc, char **argv)
{
    FILE *fpipe;
    char *cmd = "foo &> bar";

    if ( !(fpipe = (FILE*)popen(cmd,"r")) ) {
        perror("Problems with pipe");
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

Compiling: 编译:

gcc -Wall test.c -o test

The binary test creates a file called bar , which contains the following output: 二进制test创建一个名为bar的文件,其中包含以下输出:

sh: foo: command not found

Which is what I would see if I typed foo &> bar at the shell. 如果在外壳上键入foo &> bar ,那会看到什么。

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

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