atomic_get.c
1 
26 #include <unistd.h> /* for usleep() */
27 #include <errno.h>
28 #include <shm_arena.h> /* for Shared Memory Arena Library */
29 
30 
31 int main(void)
32 {
33  int *ptr;
34  int created = 0; /* bool */
35  const char *SEG_NAME = "my count";
36  size_t seg_size = sizeof(int);
37 
38 
39  /* Get exclusive access to the shared memory arena. Because this is
40  * the first Shared Memory Arena API call, his also automatically
41  * creates this local process's arena object using the default
42  * shared memory arena file. */
43  if(sm_arena_wrlock())
44  {
45  printf("Failed to get arena lock\n");
46  return 1;
47  }
48 
49  /* First check if the segment is already exists. */
50  errno = 0;
51  ptr = (int *) sm_connect(SHM_UNKNOWN_SIZE, SEG_NAME);
52 
53  if(!ptr && !errno)
54  {
55  errno = 0;
56  /* The segment does not exist so we create it */
57  ptr = (int *) sm_create(seg_size, SEG_NAME);
58 
59  if(ptr)
60  {
61  /* and initialize it, */
62  *ptr = 0;
63  created = 1;
64  }
65  }
66  else if(!errno)
67  seg_size = sm_size(ptr);
68 
69  if(!ptr)
70  {
71  printf("failed to create segment \"%s\"\n", SEG_NAME);
72  return 1;
73  }
74 
75  /* all in an atomic manner. Release exclusive access. */
77 
78  if(ptr)
79  {
80  if(created)
81  printf("Created shared memory segment \"%s\" of size %zu\n",
82  SEG_NAME, seg_size);
83  else
84  printf("Shared memory segment \"%s\" of size %zu already exists\n",
85  SEG_NAME, seg_size);
86  }
87 
88  return 0;
89 }
static size_t sm_size(const void *ptr)
get the size of a shared memory segment from a pointer
Definition: shm_arena.h:396
#define SHM_UNKNOWN_SIZE
shm_get() flag for when you don't know the segment size
Definition: shm_arena.h:165
static int sm_arena_unlock(void)
release an arena read or write lock
Definition: shm_arena.h:603
static void * sm_connect(size_t size, const char *name)
connect to a shared memory segment
Definition: shm_arena.h:379
static void * sm_create(size_t size, const char *name)
create a shared memory segment
Definition: shm_arena.h:354
static int sm_arena_wrlock(void)
acquire an arena write lock
Definition: shm_arena.h:567

Shared Memory Arena version RC-0.0.25