![Page 1: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/1.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Programação Concorrente e
Sistemas Operacionais
Edison Ishikawa
http://www.de9.ime.eb.br/~ishikawa/pg/ProgConc
![Page 2: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/2.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Introdução
• Programação concorrente• Arquiteturas
– Monoprocessadores c/ multiprogramação– Multiprocessadores
• Tecnolgia HT• Tecnologia Dual Core
– Multicomputadores• Clusters• Grid• NOW
![Page 3: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/3.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Revisão
• Estados dos processos• Controle dos processos
– Estruturas de controle – PCB, tabelas e atributos– Modos de execução
• Escalonamento– FCFS, RR, prioridades
• Trabalho– System Calls, gcc, gdb, make, cvs
• Bibliografia
![Page 4: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/4.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Trabalho
• System calls– exec…( )– fork ( )– wait ( )
• fazer programas usando as systems calls acima
![Page 5: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/5.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Como iniciar um processo em C?
• Similar a rodar um programa na linha de comando
• Usando a família de chamadas de sistemas exec…(…)– exec, execl, execv, execve, …
• exec…() troca o processo corrente pelo novo que foi especificado
![Page 6: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/6.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Exec....
• O processo que chamou exec... É completamente substituído pelo novo programa, e o novo programa inicia sua execução como se fosse a função principal (main).
• Com fork cria-se novos processos• Com exec inicia-se novos programas
![Page 7: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/7.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
exec – 6 diferentes funções
• int execl(const char *pathname, const char *arg0,.../*(char *) 0*/);
• int execv(const char *pathname, char *const argv[]);
• int execle(const char *pathname, const char *arg0, .../* (char *) 0 , char *const envp[] */);
• int execve(const char *pathname, char *argv[], char *const envp[]);
• int execlp(const char *filename, const char *arg0,.../* (char *) 0 */);
• int execvp(const char *filename, char *const argv[]);
![Page 8: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/8.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Exec
• Diferenças– 4 primeiras tem o path como argumento– 2 últimas tem um arquivo como argumento (p)
• Se o nome de arquivo contém /,é tomado como pathname
• Senão, o arquivo executável é procurado no PATH– Se o arquivo não é executável, assume que o arquivo é um
shel script e tenta invocar /bin/sh com filename como input
![Page 9: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/9.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Exec
• Diferenças– Modo de passar os argumentos
• l = lista– execl, execlp, execle
» Requer que cada um dos argumentos da linha de comando passada ao novo programa seja especificada por argumentos em separado. O último argumento é o null pointer - (char *) 0
» Ex: char* arg0, char* arg1,....,char *argn, (char *) 0
• v = vetor– execv, execvp, execve
» Os argumentos são passados em um array de ponteiros, e o endereço deste array é passado como argumento
![Page 10: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/10.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Exec
• Diferença final– e – environment
• Passagem da lista de ambiente ao novo programa através de um ponteiro de um array de ponteiros para a string de ambiente
• As outras chamadas usam a variável environ para copiar o ambiente existente para o novo programa
![Page 11: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/11.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Exec
• Propriedades– O novo programa herda do processo que o invoca
• Process ID e parent process ID• Real user ID and real group ID• Supplementary group IDs• Process group ID• Session ID• Controlling terminal• Time left until alarm clock• Current working directory• Root directory• File mode creation mask• File locks• Process signal mask• Resource limits• tms_utime, tms_stime, tms_cutime and tms ustime values
![Page 12: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/12.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
execlp execl execle
execvp execvexecve
(system call)
build argv
build argv
build argv
Relações entre as seis funções
try eachPATH prefix
useenviron
![Page 13: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/13.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
execv() - exemplo
• int execv(const char *path, char *const argv[])– path - command path– argv - argumentos (por um null no final)
• Exemplo– char* prog[3]={“/usr/bin/ps”, “-a”, NULL};– execv(prog[0], prog);
• Sugestão– consulte o man
![Page 14: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/14.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
execv – exemplo
//gcc -o execv execv.c
//Existem diversas chamadas execXXX, escolha a mais apropriada//para o trabalho
#include <stdio.h>#include <stdlib.h>
int main(){
char *my_program[3] = {"/bin/ls", "-l",NULL};
execv(my_program[0],my_program); printf("Cannot execute the command.\n"); return 0;}
![Page 15: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/15.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Como executar vários processo em um único programa C?
• System call fork()• quando um processo é “forkeado”, um novo
processo é criado• o segmento de dados e códigos do novo
processo é o mesmo do original• uma entrada na tabela de processos é criada
para o novo processo
![Page 16: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/16.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Fork
Processo 1
shell
fork
fork
Processo 1
Processo 2
PAI
FILHO
shell
shell exec
shell
ps
![Page 17: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/17.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
System call fork
• Copia o processo corrente e o executa• valor de retorno
– ZERO no processo filho– O Id do processo filho (PID) no processo pai
• use o valor de retorno para identificar aonde o programa está
![Page 18: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/18.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Exemplo de fork
#include < stdio.h>#include <sys/types.h>#include <unistd.h>
int main(){
if (fork()==0) {printf(“Eu sou o filho\n”);
} else {printf(“Eu sou o pai\n”);
}
}
Cria o processo filho
Código executado pelo filho
Código executado pelo pai
![Page 19: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/19.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
O que acontece com o processo filho quando ele morre antes que o pai?
![Page 20: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/20.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Zombie
• Quando o processo filho termina, ele tem que avisar o pai antes de se matar
• Se o pai não tomar conhecimento da morte do filho, o filho se tornará um Zombie
• O filho ficará no estado Zombie até que o pai tome conhecimento
![Page 21: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/21.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Zombie
• Os recursos usados pelo Zombie não são liberados!
• Os processos zombie são rotulados como <defunct> na listagem do comando– ps -u username
• Se o seu programa(pai) rodar por muito tempo, gerando gerações de zombies, ele irá esgotar a memória
• É obrigação do programador (sua) evitar isso
![Page 22: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/22.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Exemplo de zombie
#include <stdio.h>#include <stdlib.h>
int main(){ int pid; pid = fork(); if (pid==0){ printf(“I am child. I become a zombie now.\n”); exit (0); child process terminate here } else { printf(“I am parent. I loop here. My child pid is [%d]\n”, pid); while(1); parent process continue to run } return 0;}
![Page 23: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/23.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Como evitar o Zombie
• Usando a system call wait e waitpid no processo pai para tomar conhecimento da morte do filho
• use o man para mais info
![Page 24: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/24.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Exemplo
#include <stdio.h>#include <stdlib.h>#include <sys/wait.h>
int main(){ int pid; pid = fork(); if (pid==0){ printf(“I am child.\n”); exit (0); o processo filho termina aqui } else { printf(“I am parent. My child pid is [%d]\n”, pid); wait(NULL); espera o filho aqui while(1); } return 0;}
![Page 25: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/25.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Descritores de arquivos
• Cada processo tem sua própia tabela de descritores de arquivos para controlar todos os arquivos abertos
• Os descritores de arquivo 0 e 1 se referem ao stdin(keyboard) e ao stdout (monitor), respectivamente
• Os descritores de arquivos podem ser mudados para realizarem operações de comunicação inter-processos (operação de pipe)
![Page 26: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/26.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
System call pipe()
• int pipe(int fd[2]) ;– Dados escritos no descritor de arquivo fd[1]
pode ser lido do fd[0]
– Dois processos podem se comunicar através de um pipe se eles lêem e escrevem em fd[0] e fd[1] respectivamente
![Page 27: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/27.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
System call pipe()
pai filho
forkfd[0] fd[0]fd[1] fd[1]
kernel
pipe
![Page 28: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/28.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
System call pipe()
• O que ocorre depois do fork depende da direção dos dados. Para um pipe do pai para o filho, o pai fecha fd[0] e o filho fecha o fd[1].
pai filhofork
fd[0]fd[1]
kernel
pipe
![Page 29: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/29.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
System call dup() e dup2()
• int dup(int fd);– Duplica o descritor de arquivo (fd) e armazena-
o no descritor de menor número não usado do corrente processo
– Pode ser usado para mudar o stdin e o stdout
• int dup2(int fd1, int fd2);– Similar ao dup mas com destino especificado– fd2 = valor do novo descritor
![Page 30: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/30.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
System call dup() e dup2()
• Exemplo– newfd = dup(1)
tabela de processos
descritores de arquivos
fdofd1fd2fd3
flags ptr tabela de arquivos
file status flagcurrent file offsetv-node ptr
v-node infoi-node infocurrent file size
v-node table
![Page 31: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/31.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Exemplo usando pipe
#include <stdio.h>#include <stdlib.h>#include <sys/wait.h>
int main(){ int fd[2], pid1, pid2; char *my_program1[3] = {“/bin/ls”, “-l”, NULL}; directory listing char *my_program2[2] = {“/usr/bin/wc”, NULL}; line, word and character count
pipe(fd); if ((pid1=fork())==0){ close(1); close the stdout dup(fd[1]); duplicate fd[1] to position 1 close(fd[0]); close(fd[1]); execv(my_program1[0],my_program1); the output of the program redirected to fd[1] }if ((pid2=fork())==0){ close(0); close the stdin dup(fd[0]); duplicate the fd[0] to position 0 close(fd[0]); close(fd[1]); execv(my_program2[0],my_program2); the input of the program redirected to fd[1] } close(fd[0]); close(fd[1]); waitpid(pid1, NULL, 0); waitpid(pid2, NULL, 0); return 0;}
![Page 32: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/32.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Trabalho 1
• Fazer um programa em C/C++ que implemente pipes entre programas executáveis, como a seguinte linha de comando do UNIX
• cat arquivo.txt | grep a | grep e | grep i– Usar make, cvs e gdb
• Entregar relatório, código fonte documentado, Makefile e relatório do cvs
![Page 33: PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS Programação Concorrente e Sistemas Operacionais Edison Ishikawa ishikawa/pg/ProgConc](https://reader035.vdocuments.net/reader035/viewer/2022062303/552fc171497959413d8ee363/html5/thumbnails/33.jpg)
PROGRAMAÇÃO CONCORRENTE E SISTEMAS OPERACIONAIS
Bibliografia
• Operating Systems, 4th Ed, William Stallings, Prentice Hall
• Advanced Programming in the UNIX Environment, W. R. Stevens, Addison-Wesley
• Programming with GNU Software, M. Loukides e A. Oram, O'Reilly
• Managing Projects with make, A. Oram e S. Talbott, O'Reilly