Guest User

Untitled

a guest
Nov 23rd, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.04 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <sys/wait.h>
  5. #include <unistd.h>
  6. #include <time.h>
  7.  
  8. /*
  9. Pequano programa que mantém um processo a correr.
  10. Uso: ./daemon ./worldserver
  11. */
  12.  
  13. int main(int argc, char *argv[]){  
  14.     time_t t;
  15.     int status;
  16.     int pid;
  17.    
  18.     // verifica o numero de argumentos
  19.     if(argc != 2){
  20.         printf("Error: Invalid number of arguments\n");
  21.         return 0;
  22.     }  
  23.    
  24.     time(&t);
  25.     printf("Process Started on %s", ctime(&t));
  26.    
  27.     // corre o executável passado como argumento
  28.     pid = fork();
  29.     if(!pid) execlp(argv[1], argv[1], NULL);
  30.        
  31.     while(1){
  32.         // espera por alteração do filho
  33.         wait(&status);
  34.  
  35.         // caso o filho terminou correctamente
  36.         if(WIFEXITED(status)){
  37.             time(&t);  
  38.             printf("Process Terminated on %s", ctime(&t));
  39.             exit(0);
  40.         }
  41.        
  42.         // caso o filho terminou inesperadamente
  43.         time(&t);
  44.         printf("Crashed (signal: %d) on %s", WTERMSIG(status), ctime(&t));
  45.        
  46.         // corre o executável passado como argumento
  47.         pid = fork();
  48.         if(!pid) execlp(argv[1], argv[1], NULL);       
  49.     }
  50. }
Add Comment
Please, Sign In to add comment