librnr  1.14.5
RoadNarrows Robotics Common Library 1
example_shm.c File Reference

Example of librnr support for shared memory. More...

#include <time.h>
#include <stdio.h>
#include <string.h>
#include <libgen.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include "rnr/rnrconfig.h"
#include "rnr/log.h"
#include "rnr/opts.h"
#include "rnr/shm.h"
#include "version.h"

Go to the source code of this file.

Macros

#define N_PROCS   2
 number of processes
 
#define N_THREADS   2
 number of threads/process
 
#define WHO_CHILD   0
 child process
 
#define WHO_PARENT   1
 parent process
 
#define RED_QUEEN   0
 red queen identifier
 
#define CHESHIRE_CAT   1
 cheshire cat identifier
 
#define WHITE_QUEEN   2
 white queen identifier
 
#define MARCH_HARE   3
 march hare identifier
 
#define N_AINW_CHARS   4
 number of Alice in Wonderland characters
 
#define COLOR_RED_QUEEN   LOG_COLOR_PRE LOG_COLOR_LIGHT_RED
 red queen text color
 
#define COLOR_CHESHIRE_CAT   LOG_COLOR_PRE LOG_COLOR_LIGHT_YELLOW
 cheshire cat text color
 
#define COLOR_WHITE_QUEEN   LOG_COLOR_PRE "1;37m"
 white queen text color
 
#define COLOR_MARCH_HARE   LOG_COLOR_PRE LOG_COLOR_LIGHT_BLUE
 march hare text color
 
#define COLOR_POST   LOG_COLOR_POST
 post color string
 

Functions

static int init (int argc, char *argv[])
 Main initialization. More...
 
static void randseed ()
 Seed random number generator.
 
static void randusleep (uint_t max)
 Sleep thread for a random time. More...
 
static void lock ()
 Lock mutex.
 
static void unlock ()
 Unlock mutex.
 
static void * threadmain (void *pArg)
 Thread main. More...
 
static int createThreads ()
 Create all threads for process. More...
 
static void killThreads ()
 Kill all threads in process.
 
static void runExample (int who)
 Run example for a process.
 
int main (int argc, char *argv[])
 Example main. More...
 

Variables

static char * Argv0
 the command
 
static bool_t OptsNoMutex = false
 do [not] disable mutex
 
static bool_t OptsNoColor = false
 do [not] disable color esc sequence
 
static OptsPgmInfo_T PgmInfo
 Program information. More...
 
static OptsInfo_T OptsInfo []
 Command line options information. More...
 
key_t ShmKey = 0xdead4
 share memory key
 
shm_mutex_t ShmMutex
 share memory mutex
 
uint_t Seed
 random generator seed
 
int Who
 who: child or parent process
 
pthread_t Thread [2]
 thread
 
int ThreadState [2]
 thread run/die state
 
char * WhoName [2] = {" child", "parent"}
 process name
 
int AinWCharId [2][2]
 Alice in Wonderland character ids. More...
 
char * AinWCharName [4]
 Alice in Wonderland character names. More...
 
char * Color [4]
 Alice in Wonderland character text colors. More...
 
char * Say [4]
 Alice in Wonderland character text. More...
 

Detailed Description

Example of librnr support for shared memory.

LastChangedDate
2013-02-08 12:20:58 -0700 (Fri, 08 Feb 2013)
Rev
2676
Author
Robin Knight (robin.nosp@m..kni.nosp@m.ght@r.nosp@m.oadn.nosp@m.arrow.nosp@m.s.co.nosp@m.m)

Definition in file example_shm.c.

Function Documentation

static int createThreads ( )
static

Create all threads for process.

Returns
Ruturns 0 on success, -1 on failure.

Definition at line 312 of file example_shm.c.

References AinWCharId, LOGSYSERROR, N_THREADS, NULL, Thread, threadmain(), ThreadState, Who, and WhoName.

Referenced by runExample().

313 {
314  int i;
315 
316  for(i=0; i<N_THREADS; ++i)
317  {
318  ThreadState[i] = 1;
319 
320  if( pthread_create(&Thread[i], NULL, threadmain, &AinWCharId[Who][i]) != 0 )
321  {
322  LOGSYSERROR("%s: thread %d", WhoName[Who], i);
323  return -1;
324  }
325  }
326 
327  return 0;
328 }
int AinWCharId[2][2]
Alice in Wonderland character ids.
Definition: example_shm.c:167
int Who
who: child or parent process
Definition: example_shm.c:158
int ThreadState[2]
thread run/die state
Definition: example_shm.c:160
#define NULL
null pointer
Definition: rnrconfig.h:199
#define LOGSYSERROR(fmt,...)
Standard System Error logging.
Definition: log.h:509
char * WhoName[2]
process name
Definition: example_shm.c:162
#define N_THREADS
number of threads/process
Definition: example_shm.c:136
static void * threadmain(void *pArg)
Thread main.
Definition: example_shm.c:263
pthread_t Thread[2]
thread
Definition: example_shm.c:159
static int init ( int  argc,
char *  argv[] 
)
static

Main initialization.

Parameters
argcCommand-line argument count.
argvCommand-line argument list.
Returns
Returns 1 on success, exits on failure.

Definition at line 121 of file example_shm.c.

References Argv0, OptsGet(), and PkgInfo.

Referenced by main().

122 {
123  // name of this process
124  Argv0 = basename(argv[0]);
125 
126  // parse input options
127  argv = OptsGet(Argv0, &PkgInfo, &PgmInfo, OptsInfo, true, &argc, argv);
128 
129  return 1;
130 }
static char * Argv0
the command
Definition: example_shm.c:62
static const PkgInfo_T PkgInfo
Definition: version.h:45
char ** OptsGet(const char *argv0, const PkgInfo_T *pPkgInfo, OptsPgmInfo_T *pPgmInfo, OptsInfo_T *pOptsInfo, bool_t bHasLogging, int *pargc, char *argv[])
Gets, validates, and sets all command line options.
Definition: opts.c:861
static OptsPgmInfo_T PgmInfo
Program information.
Definition: example_shm.c:69
static OptsInfo_T OptsInfo[]
Command line options information.
Definition: example_shm.c:82
int main ( int  argc,
char *  argv[] 
)

Example main.

Parameters
argcCommand-line argument count.
argvCommand-line argument list.
Exit Status:
Program exits with 0 success, > 0 on failure.

Definition at line 398 of file example_shm.c.

References init(), LOGERROR, runExample(), WHO_CHILD, and WHO_PARENT.

399 {
400  pid_t pid;
401 
402  if( !init(argc, argv) )
403  {
404  return 2;
405  }
406 
407  switch( (pid = fork()) )
408  {
409  case -1:
410  LOGERROR("Failed to fork child process.");
411  return 8;
412  case 0: // child
414  break;
415  default: // parent
417  break;
418  }
419 
420  return 0;
421 }
#define WHO_PARENT
parent process
Definition: example_shm.c:138
#define LOGERROR(fmt,...)
Standard Error logging.
Definition: log.h:488
#define WHO_CHILD
child process
Definition: example_shm.c:137
static void runExample(int who)
Run example for a process.
Definition: example_shm.c:347
static int init(int argc, char *argv[])
Main initialization.
Definition: example_shm.c:121
static void randusleep ( uint_t  max)
static

Sleep thread for a random time.

Actual sleep time will be between [0, max].

Parameters
maxMaximum time to sleep (usec).

Definition at line 222 of file example_shm.c.

References Seed.

Referenced by runExample(), and threadmain().

223 {
224  uint_t n = (uint_t)rand_r(&Seed);
225  float r;
226  uint_t t;
227 
228  r = (float)n / (float)RAND_MAX;
229  t = (uint_t)((float)max * r);
230 
231  usleep(t);
232 }
u32_t uint_t
32-bit unsigned integer
Definition: rnrconfig.h:181
uint_t Seed
random generator seed
Definition: example_shm.c:157
static void* threadmain ( void *  pArg)
static

Thread main.

Parameters
pArgPointer to character's id.
Returns
Returns NULL.

Definition at line 263 of file example_shm.c.

References AinWCharName, Color, COLOR_POST, lock(), LOGDIAG1, N_THREADS, NULL, OptsNoColor, randusleep(), Say, ThreadState, unlock(), Who, and WhoName.

Referenced by createThreads().

264 {
265  int me = *(int *)pArg; // character id
266  int n = me - N_THREADS * Who; // thread index
267  char *sColorPre; // precolor string
268  char *sText; // characters text
269  char *sColorPost; // postcolor string
270 
271  LOGDIAG1("%s: %s thread created.", WhoName[Who], AinWCharName[me]);
272 
273  if( OptsNoColor )
274  {
275  sColorPre = "";
276  sText = Say[me];
277  sColorPost = "";
278  }
279  else
280  {
281  sColorPre = Color[me];
282  sText = Say[me];
283  sColorPost = COLOR_POST;
284  }
285 
286  while( ThreadState[n] )
287  {
288  randusleep(100000);
289 
290  lock();
291 
292  //printf("%s%s%s", sColorPre, sText, sColorPost);
293  printf("%s", sColorPre); usleep(10000);
294  printf("%s: ", AinWCharName[me]); usleep(10000);
295  printf("%s", sText); usleep(10000);
296  printf("%s", sColorPost); usleep(10000);
297  printf("\n");
298 
299  unlock();
300  }
301 
302  LOGDIAG1("%s: %s thread killed.", WhoName[Who], AinWCharName[me]);
303 
304  return NULL;
305 }
#define COLOR_POST
post color string
Definition: example_shm.c:152
char * Say[4]
Alice in Wonderland character text.
Definition: example_shm.c:196
int Who
who: child or parent process
Definition: example_shm.c:158
int ThreadState[2]
thread run/die state
Definition: example_shm.c:160
#define NULL
null pointer
Definition: rnrconfig.h:199
char * AinWCharName[4]
Alice in Wonderland character names.
Definition: example_shm.c:176
#define LOGDIAG1(fmt,...)
Standard Diagnostic Level 1 logging.
Definition: log.h:407
static void randusleep(uint_t max)
Sleep thread for a random time.
Definition: example_shm.c:222
char * Color[4]
Alice in Wonderland character text colors.
Definition: example_shm.c:185
char * WhoName[2]
process name
Definition: example_shm.c:162
#define N_THREADS
number of threads/process
Definition: example_shm.c:136
static bool_t OptsNoColor
do [not] disable color esc sequence
Definition: example_shm.c:64
static void unlock()
Unlock mutex.
Definition: example_shm.c:248
static void lock()
Lock mutex.
Definition: example_shm.c:237

Variable Documentation

int AinWCharId[2][2]
Initial value:
=
{
{ 0 , 1 },
{ 2 , 3 }
}

Alice in Wonderland character ids.

Definition at line 167 of file example_shm.c.

Referenced by createThreads().

char* AinWCharName[4]
Initial value:
=
{
"Red Queen", "Cheshire Cat",
"White Queen", "March Hare"
}

Alice in Wonderland character names.

Definition at line 176 of file example_shm.c.

Referenced by threadmain().

char* Color[4]
Initial value:
=
{
LOG_COLOR_PRE "1;37m" ,
LOG_COLOR_PRE LOG_COLOR_LIGHT_BLUE
}
#define LOG_COLOR_LIGHT_YELLOW
light yellow
Definition: log.h:240
#define LOG_COLOR_PRE
color escape sequence prefix
Definition: log.h:230
#define LOG_COLOR_LIGHT_BLUE
light blue
Definition: log.h:241
#define LOG_COLOR_LIGHT_RED
light red
Definition: log.h:238

Alice in Wonderland character text colors.

Definition at line 185 of file example_shm.c.

Referenced by threadmain().

OptsInfo_T OptsInfo[]
static
Initial value:
=
{
{
.long_opt = "no-mutex",
.short_opt = OPTS_NO_SHORT,
.has_arg = no_argument,
.has_default = true,
.opt_addr = &OptsNoMutex,
.fn_cvt = OptsCvtArgBool,
.fn_fmt = OptsFmtBool,
.arg_name = NULL,
.opt_desc = "Disable shared memory mutex."
},
{
.long_opt = "no-color",
.short_opt = OPTS_NO_SHORT,
.has_arg = no_argument,
.has_default = true,
.opt_addr = &OptsNoColor,
.fn_cvt = OptsCvtArgBool,
.fn_fmt = OptsFmtBool,
.arg_name = NULL,
.opt_desc = "Disable color coding output."
},
{NULL, }
}
int OptsCvtArgBool(const char *argv0, const char *sOptName, char *optarg, void *pOptVal)
Convert options boolean argument to bool_t.
Definition: opts.c:1018
static bool_t OptsNoMutex
do [not] disable mutex
Definition: example_shm.c:63
#define NULL
null pointer
Definition: rnrconfig.h:199
#define OPTS_NO_SHORT
no short option equivalent
Definition: opts.h:99
static bool_t OptsNoColor
do [not] disable color esc sequence
Definition: example_shm.c:64
char * OptsFmtBool(char *buf, size_t buflen, void *pOptVal)
Boolean option value string formatter.
Definition: opts.c:1247

Command line options information.

Definition at line 82 of file example_shm.c.

OptsPgmInfo_T PgmInfo
static
Initial value:
=
{
.synopsis = "Example of librnr shared memory mutex.",
.long_desc =
"The %P command forks to separate process, each with two threads that all "
"write to stdout. With mutexing enabled, the output should not be "
"intereleaved between the processes and threads."
}

Program information.

Definition at line 69 of file example_shm.c.

char* Say[4]
Initial value:
=
{
"Off with their heads, off with their heads!",
"Only the insane equate pain with success.",
"But I don't forget and I don't forgive.",
"Perhaps as this is May I won't be raving mad at least not as March."
}

Alice in Wonderland character text.

Definition at line 196 of file example_shm.c.

Referenced by threadmain().