Debian Codegraph @

listings/chapter-5/shm.c

raw
1 /***********************************************************************
2 * Code listing from "Advanced Linux Programming," by CodeSourcery LLC *
3 * Copyright (C) 2001 by New Riders Publishing *
4 * See COPYRIGHT for license information. *
5 ***********************************************************************/
6
7 #include <stdio.h>
8 #include <sys/shm.h>
9 #include <sys/stat.h>
10
11 int main ()
12 {
13 int segment_id;
14 char* shared_memory;
15 struct shmid_ds shmbuffer;
16 int segment_size;
17 const int shared_segment_size = 0x6400;
18
19 /* Allocate a shared memory segment. */
20 segment_id = shmget (IPC_PRIVATE, shared_segment_size,
21 IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
22
23 /* Attach the shared memory segment. */
24 shared_memory = (char*) shmat (segment_id, 0, 0);
25 printf ("shared memory attached at address %p\n", shared_memory);
26 /* Determine the segment's size. */
27 shmctl (segment_id, IPC_STAT, &shmbuffer);
28 segment_size = shmbuffer.shm_segsz;
29 printf ("segment size: %d\n", segment_size);
30 /* Write a string to the shared memory segment. */
31 sprintf (shared_memory, "Hello, world.");
32 /* Deatch the shared memory segment. */
33 shmdt (shared_memory);
34
35 /* Reattach the shared memory segment, at a different address. */
36 shared_memory = (char*) shmat (segment_id, (void*) 0x5000000, 0);
37 printf ("shared memory reattached at address %p\n", shared_memory);
38 /* Print out the string from shared memory. */
39 printf ("%s\n", shared_memory);
40 /* Detach the shared memory segment. */
41 shmdt (shared_memory);
42
43 /* Deallocate the shared memory segment. */
44 shmctl (segment_id, IPC_RMID, 0);
45
46 return 0;
47 }