修改popen输出并用c语言打印

时间:2013-11-16 21:53:55

标签: c stdout popen strace

以下代码生成完整的strace输出。 为什么它不会只产生前10个字符? 如何在代码中控制strace的输出?

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

#define ARRL 250

void execute_ps(){
    int count=0;
    char p;
    FILE *fp;
    char cmd[ARRL];

    //insert system command
    sprintf(cmd, "strace echo hello");
    //open channel to see output of command executed
    fp = popen(cmd,"r");
    if(fp==NULL){printf("popen err:%s\n",strerror(errno));exit(1);}
    while((p=fgetc(fp))!=EOF){
        printf("%c",p);
        if (count==10){break;}
        count++;
    }

pclose(fp);
}


int main(int argc, char **argv)
{
    execute_ps();
    exit(0);
}

1 个答案:

答案 0 :(得分:2)

strace打印到stderr,而popen仅查看stdout。完全删除print语句仍会导致产生输出。将strace echo hello更改为strace echo hello 2>&1(请参阅this)似乎可以解决问题并导致只生成10个字符。