为什么 C stdout 不返回 "ls" 命令内容?

Why is C stdout not returning "ls" command content?

我一直在做反向工作shell(不用于恶意用途)并且已经开始学习如何使用 popen 函数并使用 stdout 获取输出。我已经开始测试它,它运行良好,直到我尝试使用终端命令 "ls"。谁能指出(我假设的是)我的错误并告诉我如何解决它?

这是 C 程序的代码:

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

int main(){
    while (1){
        char* command = (char *) malloc(15*sizeof(char));
        char* output = (char *) malloc(2048);
        printf(">> ");
        scanf("%s", command);
        FILE* cmd = popen(command, "r");
        fputs(output, stdout);
        pclose(cmd);
        if (strlen(output) != 0){
            printf("\n%s\n", output);
        }
    }
}

这里是我提供给程序的输入代码,结果是:

>> cd /Users/
sh: /Users/: is a directory //output from previous command
>> >> ls                    //also why did the program print '>>' twice?
>> 


又一个问题:为什么程序打印了两次>>

代码似乎缺少 popen()(实际上是 cmd)和 output 变量之间的联系。例如,您可以使用 fread()cmd "file" 读取到 output.


调用scanf("%s", ...)一次将只扫描一个以空格分隔的单词。您的程序首先是 运行 cd,然后在下一次迭代中它是 运行 /Users/


代码通过在 while 循环中重复分配缓冲区 commandoutput 而没有 free-ing 来泄漏内存。