Usando shared memory

Publicado por Fabio Junior Sabai 23/11/2004

[ Hits: 8.300 ]

Download shared_memory.c




O GNU/Linux (e todo SO respeitável) oferece um recurso interessante para quem quer criar programas que conversem entre si. Esse recurso é a memória compartilhada, ou shared memory. Esse primeiro programa cria uma área de memória compartilhada que pode ser acessada por qualquer programa, desde que respeite as políticas de permissão, e é claro, saiba a chave, ou key, da área compartilhada. Num segundo programa estarei mostrando como se faz o acesso a essa área.

  



Esconder código-fonte

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <signal.h>

char *s;
int run = 1;

void
exit_handler(int signum)
{
    run = 0;
}

void
usr1_handler(int signum)
{
    printf("%s\n", s);
}

main()
{
    int shmid;
    struct shmid_ds buf;
    struct sigaction sig;
    char *s;

    sig.sa_flags = 0;
    sigemptyset(&sig.sa_mask);
    sig.sa_handler = exit_handler;
    sigaction(SIGTERM, &sig, NULL);
    sig.sa_handler = usr1_handler;
    sigaction(SIGUSR1, &sig, NULL);

    shmid = shmget(0xFAB10, 100, IPC_CREAT | 0600);
    if ( shmid == -1 )
    {
         printf("can't creat shared memory\n");
         perror("shmget");
         exit(1);
    }

    if ( shmctl(shmid, IPC_STAT, &buf) != 0 )
    {
         printf("can't stat shared memory\n");
         perror("shmctl");
         exit(2);
    }

    s = (char *) shmat(shmid, 0, 0);
    if ( s == (void *)-1 )
    {
         printf("can't attach shared memory\n");
         perror("shmat");
         exit(3);
    }

    strcpy(s, "ola mundo");

    while( run )
         ;

    shmdt(s);

    shmctl(shmid, IPC_RMID, 0);

    exit(0);
}

Scripts recomendados

gerador automatico de Makefiles

Busca em texto - Lista encadeada

Função "Partição de Inteiros" Recursiva SEM Tabela Estática em C

Thread, Courses, Shell e Aquivo

Fibonnaci com Memoization


  

Comentários
[1] Comentário enviado por scottys0 em 09/12/2004 - 12:31h

Isso me lembra as aulas de SO ... hehehe

[2] Comentário enviado por scottys0 em 09/12/2004 - 12:31h

Isso me lembra as aulas de SO ... hehehe e meu micro-kernel nunca funcionou ...


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts