Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Apple Xcode
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <stdlib.h>
- #include <time.h>
- #include <string.h>
- void func_simula_processamento();
- int main (int argc, const char * argv[])
- {
- int the_fork, the_status;
- // function shall create a new process
- // the new process (child process) shall be an exact copy of the
- // calling process (parent process)
- the_fork = fork();
- // getppid: shall return the parent process ID of the calling process
- printf("pid = %d, ppid = %d\n", getpid(), getppid());
- // waits for seconds or until a signal is delivered, whichever happens first
- sleep(1);
- // seed random number generator
- // 'srandom' call only needs to be done once per program
- srandom(getpid());
- char *ptr = malloc(8);
- strcpy(ptr, "pai\n");
- // the_fork == 0: == "filho": termina no exit(1)
- // apenas o filho realiza esta accao
- // as variaveis dentro deste filho nao afectam o pai ou outros filhos
- if (the_fork == 0)
- {
- // pretende demonstrar que a var alterada pelo filho nao afecta o pai
- strcpy(ptr, "filho\n");
- fwrite(ptr, 8, 1, stdout);
- // flush a stream: forca saida dos valores
- fflush(stdout);
- // a accao do filho termina aqui
- // o filho morre neste ponto
- exit(1);
- }
- // The waitpid() system call suspends execution of the calling process until a
- // child specified by pid argument has changed state. By default, waitpid()
- // waits only for terminated children, but this behavior is modifiable via the
- // options argument
- the_fork = waitpid(the_fork, &the_status, 0);
- fwrite(ptr, 8, 1, stdout);
- printf("\n");
- // WIFEXITED: this macro queries the child termination status provided
- // by the wait and waitpid functions, and determines whether the child
- // process ended normally
- if (WIFEXITED(the_status))
- {
- printf("valor de retorno de (%d): %d\n", the_fork, WEXITSTATUS(the_status));
- }
- else
- {
- printf("filho (%d) terminou de forma anormal\n", the_fork);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement