【发布时间】:2013-02-10 02:51:15
【问题描述】:
我正在编写一个 c++ 程序,它执行和输出(实时)一个 shell 脚本、makefile 或只是另一个程序。但是,当有错误或没有错误时,我希望我的程序以不同的方式返回。
#include "execxi.h"
using namespace std;
int execXI::run(string command)
{
FILE *in;
char buff[512];
// is this the check for command execution exited with not 0?
if(!(in = popen(command.c_str(), "r"))){
// I want to return the exit code and error message too if any
return 1;
}
// this part echoes the output of the command that's executed
while(fgets(buff, sizeof(buff), in)!=NULL){
cout << buff;
}
pclose(in);
return 0;
}
是我目前所拥有的。
假设这个脚本运行 make 来构建一个程序,它给出了一个这样的错误
on_target_webkit_version out/Release/obj/gen/webkit_version.h
Traceback (most recent call last):
File "../build/webkit_version.py", line 107, in <module>
sys.exit(main())
File "../build/webkit_version.py", line 103, in main
return EmitVersionHeader(*sys.argv[1:])
File "../build/webkit_version.py", line 86, in EmitVersionHeader
webkit_revision = GetWebKitRevision(webkit_dir, version_file)
File "../build/webkit_version.py", line 60, in GetWebKitRevision
version_info = lastchange.FetchVersionInfo(
AttributeError: 'module' object has no attribute 'FetchVersionInfo'
make: *** [out/Release/obj/gen/webkit_version.h] Error 1
-
我是否有可能知道这退出时出错?
因为这是一个错误,它会以代码
else than 0退出吗?最后一部分是在
stderr中输出的吗?
考虑到make 退出的代码不是0,比如说1,它在stderr 中输出,我最终无法捕获这些退出代码和错误消息吗?
如何在程序输出结果后捕获退出码和stderr,并在函数中返回exit code/stderr?
【问题讨论】:
-
pclose 返回退出状态。
标签: c++ popen stderr exit-code