C: 由 popen() 函数执行的 Linux 命令不显示结果

标签 c linux popen

我有下面的代码,我引用了 here 上的线程使用 popen 函数

int main(int argc,char *argv[]){    
    FILE* file = popen("ntpdate", "r");
    char buffer[100];
    fscanf(file, "%100s", buffer);
    pclose(file);
    printf("buffer is :%s\n", buffer);
    return 0;
}

输出:

21 Apr 03:03:03 ntpdate[4393]: no server can be used, exiting
buffer is:

为什么 printf 不输出任何东西?如果我使用 ls 作为命令,则 printf 输出 ls 输出。我在做什么错误的 ntpdate 执行?

如果我执行下面的代码(引用 webpage )

#define COMMAND_LEN 8
#define DATA_SIZE 512

int main(int argc,char *argv[]){


    FILE *pf;
       char command[COMMAND_LEN];
       char data[DATA_SIZE];

       // Execute a process listing
       sprintf(command, "ntpdate");

       // Setup our pipe for reading and execute our command.
       pf = popen(command,"r");

       if(!pf){
         fprintf(stderr, "Could not open pipe for output.\n");
         return;
       }

       // Grab data from process execution
       fgets(data, DATA_SIZE , pf);

       // Print grabbed data to the screen.
       fprintf(stdout, "-%s-\n",data);

       if (pclose(pf) != 0)
           fprintf(stderr," Error: Failed to close command stream \n");

       return 0;
}

我明白了

21 Apr 03:15:45 ntpdate[5334]: no servers can be used, exiting
-�2}�����"|�4#|�-
 Error: Failed to close command stream 

上面的代码有什么问题?

最佳答案

由于输出将转到 stderr,您需要像这样重定向 stderr:

FILE* file = popen("ntpdate 2>&1", "r");

这会将 stderr 重定向到 stdout,因此您将看到两者的输出。第二期 fscanf 将在第一个空格处停止,因此您可以用 fgets 替换:

fgets(buffer, 100, file);

关于C: 由 popen() 函数执行的 Linux 命令不显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16127027/

相关文章:

c - Sys V ABI 规范(i386 和 AMD64)中描述的标准 "Function Calling Sequence"是否适用于静态 C 函数?

python subprocess - 如何检查 PIPE 中是否没有任何新数据?

c - 加载应用程序时出现访问冲突

c - 如何定义 esp32 arduino ble 扫描结果的回调

c - 在二叉树中插入一个节点 - 将迭代转换为递归

node.js - 尝试在 MariaDB shell 中重置 Root 密码时出现语法错误

linux - 在/etc/sysconfig/network-scripts 中找不到 ifcfg-enp0s3?

c - 如何找到我的系统调用已添加到内核中?

c++ - 从在 C++ 中运行的 shell 命令永久获取输出

php - 通过 Linux 中的 Php 计算共享 Windows 驱动器上的文件