Advertisement
paulogp

Gestão de processos fork (v 1.0.1)

Jul 13th, 2011
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.03 KB | None | 0 0
  1. // Apple Xcode
  2.  
  3.  
  4. #include <stdio.h>
  5. #include <unistd.h>
  6. #include <sys/types.h>
  7. #include <sys/wait.h>
  8. #include <stdlib.h>
  9. #include <time.h>
  10. #include <string.h>
  11.  
  12. void func_simula_processamento();
  13.  
  14. int main (int argc, const char * argv[])
  15. {
  16.     int the_fork, the_status;
  17.  
  18.     // function shall create a new process
  19.     // the new process (child process) shall be an exact copy of the
  20.     // calling process (parent process)
  21.     the_fork = fork();
  22.  
  23.     // getppid: shall return the parent process ID of the calling process
  24.     printf("pid = %d, ppid = %d\n", getpid(), getppid());
  25.  
  26.     // waits for seconds or until a signal is delivered, whichever happens first
  27.     sleep(1);
  28.  
  29.     // seed random number generator
  30.     // 'srandom' call only needs to be done once per program
  31.     srandom(getpid());
  32.  
  33.     char *ptr = malloc(8);
  34.     strcpy(ptr, "pai\n");
  35.  
  36.     // the_fork == 0: == "filho": termina no exit(1)
  37.     // apenas o filho realiza esta accao
  38.     // as variaveis dentro deste filho nao afectam o pai ou outros filhos  
  39.     if (the_fork == 0)
  40.     {
  41.         // pretende demonstrar que a var alterada pelo filho nao afecta o pai
  42.         strcpy(ptr, "filho\n");
  43.         fwrite(ptr, 8, 1, stdout);
  44.  
  45.         // flush a stream: forca saida dos valores
  46.         fflush(stdout);
  47.  
  48.         // a accao do filho termina aqui
  49.         // o filho morre neste ponto
  50.         exit(1);
  51.     }
  52.  
  53.     // The waitpid() system call suspends execution of the calling process until a
  54.     // child specified by pid argument has changed state.  By default, waitpid()
  55.     // waits only for terminated children, but this behavior is modifiable via the
  56.     // options argument
  57.     the_fork = waitpid(the_fork, &the_status, 0);
  58.  
  59.     fwrite(ptr, 8, 1, stdout);
  60.  
  61.     printf("\n");
  62.  
  63.     // WIFEXITED: this macro queries the child termination status provided
  64.     // by the wait and waitpid functions, and determines whether the child
  65.     // process ended normally
  66.     if (WIFEXITED(the_status))
  67.     {
  68.         printf("valor de retorno de (%d): %d\n", the_fork, WEXITSTATUS(the_status));
  69.     }
  70.     else
  71.     {
  72.         printf("filho (%d) terminou de forma anormal\n", the_fork);
  73.     }
  74.  
  75.     return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement