this is the c code to get the pids and %cpu n %mem in linux/unix Code: FILE *fp; char pid[MAX]="ps -eo pid,pcpu,pmem"; fp=popen(pid,"r"); while (fgets(pid, MAX, fp)!=NULL) printf("%s",pid); pclose(fp); in the above code: if i give input as pid of a process, how can i get the %cpu and mem of that process only? can someone gimme the code to it? thanks in advance
Code: ps -eo pid,pcpu,pmem | awk '{if ($1==<pid_here>) print "PID\tCPU\tMEM\n" $1 "\t" $2 "\t" $3}' #example ps -eo pid,pcpu,pmem | awk '{if ($1==1389) print "PID\tCPU\tMEM\n" $1 "\t" $2 "\t" $3}' # output PID CPU MEM 1389 0.0 0.4
hii i got that in shell scripting... how do i do that in c code?? the c code which i have given has to work in linux. i want to modify the code so that when given input by user->pid of a process, it shud give the %cpu and %mem... like: printf("enter the pid; scanf("%d",pid); ....then i'm stuck here...
Code: FILE *fp; int p; printf('Enter pid: '); scanf("%d",p); char pid[MAX]=sprintf("ps -eo pid,pcpu,pmem | awk '{if ($1==%d) print \"PID\\tCPU\\tMEM\\n\" $1 \"\\t\" $2 \"\\t\" $3}'",p); fp=popen(pid,"r"); while (fgets(pid, MAX, fp)!=NULL) printf("%s",pid); pclose(fp);
i'm getting the following errors for the line with sprintf over.c:11: warning: passing arg 2 of `sprintf' makes pointer from integer without a cast over.c:11: error: invalid initializer can yu please tell me why is that?
Code: #include<stdio.h> #include<stdlib.h> #define MAX 1024 main() { FILE *fp; int p,i; char path[MAX]="ps -eo pid,pcpu,pmem"; //popen executes the command in the string fp=popen(path,"r"); printf("Enter the pid:"); scanf("%d",&p); while (fgets(path, MAX, fp)!=NULL) { //check whether the pid is there or not for(i=0;i<=MAX;i++) { if (path[i] == p) printf("%s",pid);//print the cpu n mem of that pid } fflush(fp); } pclose(fp); } input=pid of a process output=its corresponding %cpu and %mem but this is not working...someone please help me compile it.
Code: #include <stdio.h> #define MAX 50 int main(void) { FILE *fp; int p; printf("Enter pid: "); scanf("%d",&p); unsigned char pid[MAX]; char out[25]; sprintf(pid,"ps -eo pid,pcpu,pmem | awk '{if ($1==%d) print \"PID\\tCPU\\tMEM\\n\" $1 \"\\t\" $2 \"\\t\" $3}'",p); fp=popen(pid,"r"); while (fgets(out, MAX, fp)!=NULL) puts(out); pclose(fp); return 0; }