Unix上的C++:重定向Shell输出
C++ on Unix: Redirecting Shell Output
我有一个编译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
,我会看到这种情况。
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用提升过程获取 shell 命令的标准输出
- 在结束运行之前获取 c++ 中的 shell 命令输出
- 为什么在Shell输出中运行的可执行操作到stdout,而不是崩溃时的stderr
- C++使用 shell 命令 WINDOWS 的输出定义宏 /D
- 程序在cmd中工作,在cygwin中立即以状态127退出,在emacs shell中没有输出
- 从c++程序运行shell脚本会自动将shell脚本的输出显示到控制台吗
- 在 c++ 中执行 Linux shell 命令,同时隐藏其输出
- 我想获取用户输入并将其输出到我的 shell 环境中
- Shell脚本终止程序,但导致无法写入输出文件
- 如何从system()获得shell输出
- 重复调用 shell 命令,通过管道捕获标准输出
- 微软nmake:是否可以从shell命令输出中定义宏
- 使用C++或Bash/Shell脚本评估后台linux命令的输出
- Unix上的C++:重定向Shell输出
- GNU Make -在规则/目标中设置shell命令输出中的MAKEFILE变量
- 执行 bash shell 命令并提取输出 -->无效文件错误
- C++ 中非终止 Linux shell 执行的 Fechting 输出