【发布时间】:2010-09-23 11:53:32
【问题描述】:
我正在使用以下代码尝试在 Linux 中使用 popen 读取 df 命令的结果。
#include <iostream> // file and std I/O functions
int main(int argc, char** argv) {
FILE* fp;
char * buffer;
long bufSize;
size_t ret_code;
fp = popen("df", "r");
if(fp == NULL) { // head off errors reading the results
std::cerr << "Could not execute command: df" << std::endl;
exit(1);
}
// get the size of the results
fseek(fp, 0, SEEK_END);
bufSize = ftell(fp);
rewind(fp);
// allocate the memory to contain the results
buffer = (char*)malloc( sizeof(char) * bufSize );
if(buffer == NULL) {
std::cerr << "Memory error." << std::endl;
exit(2);
}
// read the results into the buffer
ret_code = fread(buffer, 1, sizeof(buffer), fp);
if(ret_code != bufSize) {
std::cerr << "Error reading output." << std::endl;
exit(3);
}
// print the results
std::cout << buffer << std::endl;
// clean up
pclose(fp);
free(buffer);
return (EXIT_SUCCESS);
}
这段代码给了我一个“内存错误”,退出状态为“2”,所以我可以看到 哪里它失败了,我只是不明白 为什么.
我从在 Ubuntu Forums 和 C++ Reference 上找到的示例代码中将其组合在一起,所以我并没有与之结婚。如果有人可以提出更好的方法来读取 system() 调用的结果,我愿意接受新的想法。
编辑原文:好的,bufSize 的结果是否定的,现在我明白为什么了。您不能像我天真地尝试那样随机访问管道。
我不能成为第一个尝试这样做的人。有人可以给出(或指出)如何将 system() 调用的结果读入 C++ 中的变量的示例吗?
【问题讨论】:
-
'系统调用'有一个非常具体的含义 - 参见 en.wikipedia.org/wiki/System_call>。你试图做什么来捕获另一个程序的输出(我不确定这个的技术术语是什么)。
-
谢谢。我编辑了问题以尝试澄清。
标签: c++ linux operating-system system-calls