我执行了一个命令“watch grep \”cpu MHz \“/ proc / cpuinfo”。执行此命令后,我得到了以下结果。 Result of The Command
但是当我使用c代码尝试此命令时。
#include<stdio.h>
#include<stdlib.h>
int main(){
FILE *fp;
char path[1035];
char command[]="watch grep \"cpu MHz \" /proc/cpuinfo";
fp = popen(command, "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit(1);
}
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("%s",path);
}
pclose(fp);
return 0;
}
I am getting following result.
Result of The Code 告诉我哪里出错了?
答案 0 :(得分:1)
尝试这样的事情:
#include <stdio.h>
#include <stdlib.h>
int main(void){
FILE *fp;
char path[1035];
char command[]="while grep \"cpu MHz\" /proc/cpuinfo; do sleep 2; done";
fp = popen(command, "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit(1);
}
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path), fp) != NULL) {
printf("%s",path);
}
pclose(fp);
return 0;
}
答案 1 :(得分:0)
我认为这就是你想要的。
不要忘记使用memset
。
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;
char path[1035];
char command[]="watch grep 'cpu MHz' /proc/cpuinfo";
fp = popen(command, "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit(1);
}
memset(path,'\0',sizeof(path));
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("%s",path);
}
pclose(fp);
return 0;
}