System V下shared memory编程实例

王朝system·作者佚名  2006-01-10
窄屏简体版  字體: |||超大  

例1:

#include <stdio.h>

#include <sys/shm.h>

#include <sys/stat.h>

#include <sys/types.h>

#include <sys/ipc.h>

int main ()

{

int segment_id;

char* shared_memory;

struct shmid_ds shmbuffer;

int segment_size;

key_t keys;

const int shared_segment_size = 0x6400;

keys= ftok("/usr", 'a');

/* Allocate a shared memory segment. */

segment_id = shmget (keys, shared_segment_size,IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);

/* Attach the shared memory segment. */

shared_memory = (char*) shmat (segment_id, 0, 0);

printf ("shared memory attached at address %p\n", shared_memory);

/* Determine the segment’s size. */

shmctl (segment_id, IPC_STAT, &shmbuffer);

segment_size = shmbuffer.shm_segsz;

printf ("segment size: %d\n", segment_size);

/* Write a string to the shared memory segment. */

sprintf (shared_memory, "Hello, world.");

/* Detach the shared memory segment. */

shmdt (shared_memory);

/* Reattach the shared memory segment, at a different address. */

shared_memory = (char*) shmat (segment_id, (void*) 0x5000000, 0);

printf ("shared memory reattached at address %p\n", shared_memory);

/* Print out the string from shared memory. */

printf ("%s\n", shared_memory);

/* Detach the shared memory segment. */

shmdt (shared_memory);

sleep(10);

/* Deallocate the shared memory segment. */

shmctl (segment_id, IPC_RMID, 0);

return 0;

}

例2:

#include <stdio.h>

#include <sys/shm.h>

#include <sys/stat.h>

#include <sys/types.h>

#include <sys/ipc.h>

int main ()

{

int segment_id;

char* shared_memory;

struct shmid_ds shmbuffer;

int segment_size;

key_t keys;

const int shared_segment_size = 0x6400;

keys= ftok("/usr", 'a');

/* Allocate a shared memory segment. */

segment_id = shmget (keys, shared_segment_size, S_IRUSR | S_IWUSR);

/* Attach the shared memory segment. */

if (segment_id < 0)

{

printf("Cannot get share memory\n");

return -1;

}

shared_memory = (char*) shmat (segment_id, 0, 0);

printf ("shared memory attached at address %p\n", shared_memory);

/* Determine the segment’s size. */

shmctl (segment_id, IPC_STAT, &shmbuffer);

segment_size = shmbuffer.shm_segsz;

printf ("segment size: %d\n", segment_size);

/* Print out the string from shared memory. */

printf ("shared_memory: %s\n", shared_memory);

/* Detach the shared memory segment. */

shmdt (shared_memory);

return 0;

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航