gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:53:12 24 4
gpt4 key购买 nike

以下代码生成完整的 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);
}

最佳答案

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

关于c - 修改popen输出并用c语言打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20024371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com