我有下面的代碼我指上here線程使用popen
函數Linux命令
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'來查看輸出 – 2013-04-21 01:24:53