【问题标题】:Why is C stdout not returning "ls" command content?为什么 C stdout 不返回“ls”命令内容?
【发布时间】:2020-04-11 18:54:49
【问题描述】:

我一直在研究反向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?
>> 


另一个问题:为什么程序会打印两次&gt;&gt;

【问题讨论】:

    标签: c terminal stdout popen


    【解决方案1】:

    代码似乎缺少popen()(实际上是cmd)和output 变量之间的连接。例如,您可以使用fread()cmd“文件”读入output


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


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

    【讨论】:

    • 如何连接popen和输出变量?
    • 请参阅上面的答案:例如,您可以使用fread()cmd“文件”读取output
    猜你喜欢
    • 2020-12-25
    • 1970-01-01
    • 2023-03-19
    • 2018-11-26
    • 1970-01-01
    • 2023-03-12
    • 2016-10-12
    • 2021-06-10
    • 2016-11-15
    相关资源
    最近更新 更多