c - fgets 为 popen 返回的 FILE 返回错误

标签 c popen fgets

我试图从我的 C 代码执行命令行,但是当我到达 fgets() 函数时,我收到了 NULL 错误。

void executeCommand(char* cmd, char* output) {
    FILE *fcommand;
    char command_result[1000];
    fcommand = popen(cmd, "r");
    if (fcommand == NULL) {
        printf("Fail: %s\n", cmd);
    } else {
        if (fgets(command_result, (sizeof(command_result)-1), fcommand) == NULL)
             printf("Error !");
        strcpy(output, command_result);
    }
    pclose(fcommand);
}

我的命令是:

java -jar <parameters>

为什么我从 fgets 得到 NULL 结果,尽管当我尝试在终端中执行相同的命令时,它按预期工作。

最佳答案

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer.

简而言之,popen() 正在执行 fork() 并且您正尝试在 cmd< 调用程序之前从管道中读取数据 产生了输出,因此管道上没有数据,管道上的第一次读取将返回 EOF,因此 fgets() 返回时没有获取数据。您要么需要 sleep ,要么进行轮询,要么进行阻塞读取。

关于c - fgets 为 popen 返回的 FILE 返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15882799/

相关文章:

c - fgets 未读取整行,未遇到新行字符

ios - 在二进制数据中查找字符串

c - 以下 C char 数组存储实现背后的原因是什么?

使用 1990 年 1 月 1 日作为纪元日期将天数转换为 C 中的日期

python - 在 python 中包装交互式 CLI

python子进程popen将主目录设置为cwd

python - hg verify 不返回 0 或 1

c - 读取带有换行符和空格的字符串

c - 从不兼容的指针类型传递参数 3 of “fgets ”

从 C 函数更改 gtk_tree_selection 中的选定行