【问题标题】:C++ on Unix: Redirecting Shell OutputUnix 上的 C++:重定向 Shell 输出
【发布时间】:2012-02-23 03:37:06
【问题描述】:

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

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

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

我也尝试过使用 popen()fgets()(只是从 here 复制代码),但同样发生了。我可能可以只分叉我的进程并使用 freopen 或其他东西,但我有套接字和多个线程在后台运行。我猜它们也会被复制,这不好。

任何想法为什么它可能会失败?

【问题讨论】:

  • 你在哪个平台上?根据我本地 Linux 安装上的 system 手册页,它专门使用 /bin/sh 来执行字符串。 shell 之间的重定向语法不同,&> 可能是 bash 扩展。 /bin/sh 是否是 bash 的符号链接可能取决于平台/发行版。
  • 我使用的是 Ubuntu 11.10。

标签: c++ shell system


【解决方案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 &amp;&gt; bar,我会看到什么。

【讨论】:

    【解决方案2】:

    根据system 的手册页,它调用sh,这是标准的bourne shell(不是bash,Bourne Again SHell)。而且 bourne shell 不理解&amp;&gt;。所以你可能需要使用旧样式:

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

    【讨论】:

    • 工作就像一个魅力。谢谢。将在 5 分钟内标记为答案。
    猜你喜欢
    • 2011-04-26
    • 2016-03-10
    • 2014-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多