I want to print the percent of cpu for idle process in my c program.
-
if pclose(ptr) is used (this means I just want hogs run only once).
the program can’t print the message I want, just print the message
about the broken pipe. (if use fd , the program run correctly. I know
this problem occurs because hogs update message every 3 seconds . but
I just want to print message only once.) -
if pclose(ptr) isn’t used (this means print the message all the
time ) , the program can’t print the message immediately. I have
tried fflush(stdout) and setvbuf为_IONBF,but still can’t solve it
I don’t know how to slove this two programs. Thanks.
char *cmd = “hogs | awk ‘{if($1==1)print$4}’”;
// char *cmd = “hogs | awk ‘{print$4}’”;
char buf [10];
FILE *ptr;
short idlecpu;
if ((ptr = popen(cmd, “r”)) != NULL)
if(fgets(buf,10, ptr) != NULL)
{
if(fgets(buf,10, ptr) != NULL)
idlecpu=atoi(buf);
printf(“idlecpu=%d \n”,idlecpu);
printf("%s ",buf);
}
pclose(ptr);
printf(“exit!”);