C语言如何从popen()函数中读取stdout存入char数组?

How to read the stdout from the popen() function and store it in the char array in C language?

好吧,我在将 stdout 输出发送到数组时遇到了困难。我该如何解决这个问题?我需要将带有执行代码的 bash 命令输出从服务器发送回客户端。协议是TCP。谢谢!

     void func(int sockfd)
     { 
        char buff[MAX]; 
        for (;;) 
        { 
            bzero(buff, MAX); 
            read(sockfd, buff, sizeof(buff)); 
            printf("From client: %s\n", buff);
            if (strncmp("exit", buff, 4) == 0) 
            { 
                printf("Server Exit...\n"); 
                write(sockfd, buff, sizeof(buff));
                break; 
            } 
            FILE *cmd=popen(buff,"r");
            while (fgets(buff, sizeof(buff), cmd))
            strcpy(buff,cmd);
            pclose(cmd);
            write(sockfd, buff, sizeof(buff)); 
            my_itoa(system(buff),buff);
            write(sockfd, buff, sizeof(buff));          
        } 
     } 

我猜您想将 bash 命令的执行结果发送回客户端。您可以将代码更改为每次从 cmd 获取一行字符时都写入 sockfd。

FILE* cmd=popen(buff, "r");
while(fgets(buff, sizeof(buff), cmd))
{
  write(sockfd, buff, strlen(buff));  // sizeof() will write more than you actually read.
}
pclose(cmd);