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

C++ on Unix: Redirecting Shell Output

本文关键字:Shell 输出 重定向 上的 C++ Unix      更新时间:2023-10-16

我有一个编译test.cpp的命令,应该将输出存储在输出文件中。以下是我生成的cmd:的示例

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

当我使用system()时,它不起作用。即使它创建了输出文件,它仍然会将所有内容打印到主控制台窗口。当我在终端中执行它时,它运行得很好。

我还尝试使用popen()fgets()(只是从这里复制代码),但发生了同样的情况。我可能只需要分叉我的进程并使用freopen之类的东西,但我有套接字和多个线程在后台运行。我想它们也会被复制,这不好。

你知道它为什么会失败吗?

根据system的手册页,它调用sh,这是标准的bourne shell(而不是bash,bourne Again shell)。而bourne shell不理解&>。因此,您可能需要使用旧样式:

g++ tmp/test.cpp -o tmp/test >tmp/compile.out 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;
}

编译:

gcc -Wall test.c -o test

二进制test创建一个名为bar的文件,其中包含以下输出:

sh: foo: command not found

如果我在shell中键入foo &> bar,我会看到这种情况。