segunda-feira, 28 de dezembro de 2009

Shared memory hello world

/*
 * file: shared-memory-write.c
 */

#include <stdio.h>
#include <sys/shm.h>


int
main (void)
{
  key_t key = 2525;
  char * shared_memory;
  int segment_size = 0x6400;
  int segment_id;
  
  segment_id = shmget (key, segment_size, IPC_CREAT | 0666);
  shared_memory = shmat (segment_id, NULL, 0);
  sprintf (shared_memory, "Hello World");
  
  while (1)
 sleep (1);
  
  return 0;
}

/*
 * file: shared-memory-read.c
 */

#include <stdio.h>
#include <sys/shm.h>

int 
main (void)
{
  int segment_id; 
  key_t key = 2525;
  char * shared_memory;
  int segment_size = 0x6400;
  
  segment_id = shmget (key, segment_size, 0666);
  shared_memory = shmat (segment_id, NULL, 0);
  printf ("%s\n", shared_memory);
  
  shmdt (shared_memory);
  shmctl (segment_id, IPC_RMID, 0);

  return 0;
}
run ./shared-memory-write
and in another shell ./shared-memory-read.c
then in first shell kill shared-memorr-write with Ctrl-c

Nenhum comentário:

Postar um comentário