c语言调用system返回127,如何在C中读取system()调用的结果?

我正在使用以下代码尝试使用popen在Linux中读取df命令的结果.

#include // 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即将消极,现在我理解为什么.您不能随意访问管道,因为我天真地试图这样做.

我不能成为第一个尝试这样做的人.有人可以给(或指向我)一个如何将系统()调用结果读入C中的变量的示例吗?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值