C: popen() 函数执行的 Linux 命令不显示结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16127027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C: Linux command executed by popen() function not showing results
提问by sven
I have the code below that I refer the thread on hereto use the popen
function
我有下面的代码,我在这里引用线程来使用该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;
}
It outputs:
它输出:
21 Apr 03:03:03 ntpdate[4393]: no server can be used, exiting
buffer is:
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?
为什么printf
不输出任何东西?如果我ls
用作命令,则 printf 输出 ls 输出。我在做什么错ntpdate
执行?
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;
}
I get
我得到
21 Apr 03:15:45 ntpdate[5334]: no servers can be used, exiting
-?2}?????"|?4#|?-
Error: Failed to close command stream
what are wrongs on the codes above?
上面的代码有什么问题?
采纳答案by Shafik Yaghmour
Since the output is going to stderr
you need to redirect stderr
like so:
由于输出将要发送给stderr
您,stderr
因此您需要像这样重定向:
FILE* file = popen("ntpdate 2>&1", "r");
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
:
这将重定向stderr
到stdout
,因此您将看到两者的输出。第二个问题fscanf
将在第一个空格处停止,因此您可以替换为fgets
:
fgets(buffer, 100, file);
回答by Jonathan Leffler
As Shafik Yaghmourcorrectly diagnosed, the output you see from ntpdate
is written (correctly) to its standard error, which is the same as your programs standard error.
正如Shafik Yaghmour正确诊断的那样,您看到的输出ntpdate
被(正确)写入其标准错误,这与您的程序标准错误相同。
To get the error messages sent down the pipe, use:
要获取通过管道发送的错误消息,请使用:
FILE *file = popen("ntpdate 2>&1", "r");
That sends the standard error output from ntpdate
to the standard output of the command, which is the pipe you're reading from.
ntpdate
它将标准错误输出发送到命令的标准输出,即您正在读取的管道。
Of course, it looks like using ntpdate
isn't going to work well until you've configured something.
当然,ntpdate
在您配置某些内容之前,看起来使用不会很好地工作。