【问题标题】:C: Linux command executed by popen() function not showing resultsC:popen() 函数执行的 Linux 命令未显示结果
【发布时间】:2013-04-14 04:04:06
【问题描述】:

我有下面的代码,我参考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 

上面的代码有什么问题?

【问题讨论】:

  • 如果我们做ntpdate 2>/dev/null,我们可以看到它正在使用stderr,所以你需要重定向stderr才能看到输出

标签: c linux popen


【解决方案1】:

正如Shafik Yaghmour 正确诊断,您从ntpdate 看到的输出被(正确)写入其标准错误,这与您的程序标准错误相同。

要获取通过管道发送的错误消息,请使用:

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

这会将来自ntpdate 的标准错误输出发送到命令的标准输出,也就是您正在读取的管道。

当然,在您配置某些内容之前,使用ntpdate 似乎无法正常工作。

【讨论】:

    【解决方案2】:

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

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

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

    fgets(buffer, 100, file);
    

    【讨论】:

    • 这里只输出buffer is :21,服务器定义在/etc/ntp.conf。如果我使用 FILE* file = popen("ntpdate 79.99.6.190 2>&1", "r"); ,则 79.99.6.190 是 pool.ntp.org 的 ntp 服务器。我错过了什么吗?这就是我如何使用代码pastebin.com/8g77zRF0
    • 非常感谢 Shafik Yaghmour!
    猜你喜欢
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 2023-04-05
    相关资源
    最近更新 更多