Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.11 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <time.h>
  4. #include <stdlib.h>
  5. #include <errno.h>
  6. #include <sys/wait.h>
  7. #include <string.h>
  8. #include <sys/types.h>
  9.  
  10. int main (int argc, char *argv[], char *envp[]) {
  11.  
  12.     int pid = fork(); // The 'pid' identifies the process that is running.
  13.     char comma[100], save_pid[100];
  14.  
  15.     // Check if the fork failed
  16.     if (pid < 0) {
  17.         perror ("Error: ");
  18.         exit(-1); // End the process with an error code (-1)
  19.    
  20.     } else if (pid == 0) { // I'm the child process
  21.  
  22.         if(strcmp(argv[1], "ucp") == 0) { // Check if argv[1] is "ucp" to monitor cpu usage
  23.             for (;;) {}                  // Infinite loop that is cpu intensive
  24.         } else if(strcmp(argv[1], "ucp-mem") == 0) { // Check if argv[1] is "ucp-mem" to monitor cpu and memory usage
  25.             for (;;) {                  // Infinite loop that is cpu and memory intensive
  26.                 malloc(sizeof(char));   // Memory allocation
  27.             }
  28.         }
  29.    
  30.     } else {  // I'm the parent process
  31.         sprintf(save_pid, "%d", pid); // Save the current process identifier
  32.        
  33.         if (strcmp (argv[1], "ucp") == 0) {
  34.            
  35.             printf ("# CPU USAGE #\n");
  36.             strcpy(comma, "ps -e -o pid,pcpu | grep "); // Save in 'comma' the bash command
  37.             strcat(comma, save_pid); // Concatenate the bash command and the saved pid
  38.        
  39.         } else if (strcmp (argv[1], "ucp-mem") == 0) {
  40.  
  41.             printf ("# CPU AND MEMORY USAGE #\n");
  42.             strcpy(comma, "ps -e -o pid,pcpu | grep ");
  43.             strcat(comma, save_pid);
  44.             strcat(comma, ";pmap "); // Show the memory consumption
  45.             strcat(comma, save_pid);
  46.             strcat(comma, " | grep -i total");
  47.         }
  48.    
  49.         for (int cont = 0; cont < 3; cont++) {
  50.             system(comma);
  51.             usleep(500000);
  52.         }
  53.         strcpy(comma, "kill "); // Kill the child process
  54.         strcat(comma, save_pid);
  55.         system(comma);
  56.     }
  57.  
  58.     perror("Error: ");
  59.  
  60.     exit(0); // Terminate the process with success
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement