我有下面的代码,我在
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执行?
#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