C:popen()函数执行的Linux命令未显示结果 [英] C: Linux command executed by popen() function not showing results
问题描述
我有下面的代码,我在在这里使用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?
如果我执行以下代码(请参考网页)
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
上面的代码有什么错误?
what are wrongs on the codes above?
推荐答案
由于输出将发送到stderr
,因此您需要像这样重定向stderr
:
Since the output is going to stderr
you need to redirect stderr
like so:
FILE* file = popen("ntpdate 2>&1", "r");
这会将stderr
重定向到stdout
,因此您将看到两者的输出.第二期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);
这篇关于C:popen()函数执行的Linux命令未显示结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!