Skip to content

Instantly share code, notes, and snippets.

@kleberandrade
Created March 15, 2016 17:31
Show Gist options
  • Save kleberandrade/c459f5180cf5fce00188 to your computer and use it in GitHub Desktop.
Save kleberandrade/c459f5180cf5fce00188 to your computer and use it in GitHub Desktop.
Método de compartilhar informações entre processos utilizando um arquivo
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
int main(int argc, char *argv[])
{
int pid, fd, i,r;
char *pidnum, c;
printf("Meu PID=%d\n", getpid());
printf("Gravando o numero do meu PID...\n");
// Criar um arquivo
if ((fd = open("meupid", O_WRONLY | O_CREAT | O_EXCL, 0777)) == -1)
{
// Abrir arquivo para escrita caso já exista
if ((fd = open("meupid", O_WRONLY)) == -1)
{
printf("Nao consegui criar o arquivo.\n");
exit(-1);
}
else
{
printf("Arquivo aberto com sucesso.\n");
}
}
else
{
printf("Arquivo criado com sucesso.\n");
}
// Escrever "pid surpresa" dentro do arquivo
sprintf(pidnum, "%d surpresa", getpid());
if (write(fd,pidnum,15) == -1)
{
printf("Nao consegui escrever no arquivo.\n");
exit(-1);
}
else
{
printf("Mensagem \"%s\" gravada no arquivo.\n", pidnum);
}
// Fecha o arquivo
close(fd);
// Abrir o arquivo somente para leitura
if ((fd = open("meupid", O_RDONLY)) == -1)
{
printf("Nao consegui ler o arquivo.\n");
exit(-1);
}
else
{
printf("Arquivo aberto para leitura com sucesso.\n");
}
printf("Criando o processo filho.\n");
pid=fork();
if (pid == -1)
{
printf("Erro ao criar o filho.\n");
exit(-1);
}
else if(pid==0)
{ //filho
for (i = 0 ; i < 5 ; i++)
{
if (read(fd,&c,1) == -1)
{
printf("Erro ao ler o arquivo.\n");
exit(-1);
}
printf("Li o numero %c\n",c);
}
close(fd); //fecha o arquivo
printf("Filho fecha o arquivo.\n");
exit (1);
}
else
{
wait(0);
printf("Pai executando...\n");
while ((r = read (fd,&c,1)) !=0)
{
if (r == -1)
{
printf("Impossivel ler o arquivo.\n");
exit(-1);
}
printf("Consegui ler %c\n",c);
}
printf("O filho modificou o ponteiro ao ler o arquivo\n");
printf("Pai finalizando...\n");
close(fd); //fecha o arquivo
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment