Making a program that shows CPU(%) and Memory usage(kB) using pid linux

Refresh

November 2018

Views

64 time

2

I'm trying to create a program that gets the CPU(%) and Memory(kB) usage to show it on Ubuntu Terminal. I've been searching for some command that shows me it, and i got that;

ps -p <pid> -o %cpu,%mem

When I test it directly on terminal, it works just fine. But on my program it gives me that error: error: garbage option

Here's my code:

#include <unistd.h>
#include<time.h>
#include <stdio.h>
#include <stdlib.h>
#include<string.h>

int main (int argc, char *argv[], char *envp[]) {
   int pid ; /* Process ID */
   char usage[150];
   char kill[50];
   pid = fork () ; /* Process reaplication */
   sprintf(usage,"%s%d%s","ps -p ", pid,  " %cpu,%mem");
   sprintf(kill, "%s%d", "kill -9 ", pid);

   if ( pid < 0 ) { /*if fork do not work*/
       perror ("Erro: ") ;
       exit (-1) ; /* Ends process with error: -1 */
   } else if( pid > 0 ) { /* If i'm parent process*/
       for(int i=0;i<10;i++) {
          system("clear");
          printf("Processing (%ds)\n", i);
          int aux;
          for(aux=i;aux>0;aux--) {
              printf("=");
          }
          printf("=\n");
          system(usage);
          sleep(1);
       }
       system(kill);
   } else /* senão, sou o processo filho (pid == 0) { */
      if(strcmp(argv[1],"cpu")==0) { /* if argv[1] = cpu -> Execute code using intese cpu*/
         for(;;){}
      }
      if(strcmp(argv[1],"cpu-mem")) { /* if argv[1] = cpu-mem -> Execute code using intese cpu and memory */
         int moment = clock();
         for (;;) {
            while(clock() - moment < 5){} /* makes mem use less intense  */
            malloc(sizeof(1000));
         }
      }
   }
   perror ("Erro: ") ; /* if do not work */
   printf ("Tchau !\n") ;
   exit(0) ; /* Ends process with success (código 0) *
}

So, I'm trying to divide the program in 10 steps. Each one is gonna execute the command. There is one sec between the steps

How can I get this code to work? Is there any other commands that I can use to replace this one?

1 answers

2

Уже решили. Вот как я сделал:

#include <unistd.h>
#include<time.h>
#include <stdio.h>
#include <stdlib.h>
#include<string.h>

int main (int argc, char *argv[], char *envp[]) {
int pid ; /* Process ID */
char mem_usage[50];
char cpu_usage[50];
char kill[50];
pid = fork () ; /* Process reaplication */
sprintf(cpu_usage,"%s%d%s","ps -p ", pid, " -o %cpu | grep -v %CPU");
sprintf(mem_usage, "%s%d%s", "pmap -x ", pid," | grep total | awk '{print $3}'");
sprintf(kill, "%s%d", "kill -9 ", pid);

if ( pid < 0 ) { /*if fork do not work*/
    perror ("Erro: ") ;
    exit (-1) ; /* Ends process with error: -1 */
}
else if( pid > 0 ) /* If i'm parent process*/
{
    for(int i=0;i<10;i++)
  {
    system("clear");
    if(i == 0 || i == 3 || i == 6 || i == 9)
    {
    printf("Processing.\n");
    }
    else if(i == 1 || i == 4 || i == 7)
    {
      printf("Processing..\n");
    }
    else if(i == 2 || i == 5 || i == 8)
    {
      printf("Processing...\n");
    }
    printf("%ds\n", i+1);
    printf("================\n");
    printf("CPU(%%)\n");
    system(cpu_usage);
    printf("MEM(kB)\n");
    system(mem_usage);
    sleep(1);
  }
  system(kill);
}
else /* senão, sou o processo filho (pid == 0) */
{
  if(strcmp(argv[1],"cpu")==0) /* if argv[1] = cpu -> Execute code using intese cpu*/
  {
    for(;;){}
  }
  if(strcmp(argv[1],"cpu-mem")==0) /* if argv[1] = cpu-mem -> Execute code using intese cpu and memory */
  {
    int moment = clock();
    for (;;) {
        sleep(0.001); /* makes mem use less intense  */
    malloc(50* sizeof(int));
}
  }

}
perror ("Erro: ") ; /* if do not work */

printf ("Tchau !\n") ;
exit(0) ; /* Ends process with success (código 0) */

}

Я использовал , ps -p <pid> -o %cpu | grep -v %CPUчтобы получить CPU (%) использование.

Для расчета памяти (кБ) Использование:pmap -x <pid> " | grep total | awk '{print $3}'"

В этом случае, я использовал , awk '{print $3}'чтобы напечатать третий столбец из Comand pmap -x <pid>и grep totalпечатать только линию я нуждался.

Есть два способа запустить этот код:

    1. ./filename процессора ---> Будет только «Force» ваш процессор
    1. ./filename CPU-ает ---> Собирается использовать RAM, это может привести к аварийному вашему компьютеру.

Это хорошее упражнение, чтобы узнать, как CPU и память работать.