linux命令由popen这基于C code执行 [英] linux command executing by popen on C code

查看:374
本文介绍了linux命令由popen这基于C code执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code我指的<一个线程href=\"http://stackoverflow.com/questions/671461/how-can-i-execute-external-commands-in-c-linux\">here使用的popen 函数

I have the code below that I refer the thread on here to use the popen function

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 执行?

why printf does not output anything? If I use ls as a command, then printf outputs the ls output. what am I doing wrong ntpdate executing?

如果我执行以下(指的网页上的code

If I execute the code below (referring the 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 

什么是在codeS上面的过错?

what are wrongs on the codes above?

推荐答案

由于输出将会标准错误您需要重定向标准错误像这样:

Since the output is going to stderr you need to redirect stderr like so:

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

这将标准错误重定向到标准输出键,所以你会看到两个输出。第二个问题的fscanf 将在第一次太空停止,所以你可以用替换与fgets

this will redirect stderr to stdout and so you will see output from both. Second issue fscanf will stop at the first space so you can replace with fgets:

fgets(buffer, 100, file);

这篇关于linux命令由popen这基于C code执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆