This example_shm page provides an example of librnr support for shared memory.
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <libgen.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
{
.
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."
};
{
{
.has_arg = no_argument,
.has_default = true,
.opt_desc = "Disable shared memory mutex."
},
{
.long_opt = "no-color",
.has_arg = no_argument,
.has_default = true,
.opt_desc = "Disable color coding output."
},
};
static int init(
int argc,
char *argv[])
{
Argv0 = basename(argv[0]);
argv =
OptsGet(Argv0, &
PkgInfo, &PgmInfo, OptsInfo,
true, &argc, argv);
return 1;
}
#define N_PROCS 2
#define N_THREADS 2
#define WHO_CHILD 0
#define WHO_PARENT 1
#define RED_QUEEN 0
#define CHESHIRE_CAT 1
#define WHITE_QUEEN 2
#define MARCH_HARE 3
#define N_AINW_CHARS 4
#define COLOR_RED_QUEEN LOG_COLOR_PRE LOG_COLOR_LIGHT_RED
#define COLOR_CHESHIRE_CAT LOG_COLOR_PRE LOG_COLOR_LIGHT_YELLOW
#define COLOR_WHITE_QUEEN LOG_COLOR_PRE "1;37m"
#define COLOR_MARCH_HARE LOG_COLOR_PRE LOG_COLOR_LIGHT_BLUE
#define COLOR_POST LOG_COLOR_POST
{
};
{
"Red Queen", "Cheshire Cat",
"White Queen", "March Hare"
};
{
};
{
"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."
};
{
struct timespec t;
clock_gettime(CLOCK_REALTIME, &t);
}
{
float r;
r = (float)n / (float)RAND_MAX;
usleep(t);
}
{
if( !OptsNoMutex )
{
}
}
{
if( !OptsNoMutex )
{
}
}
{
int me = *(int *)pArg;
char *sColorPre;
char *sText;
char *sColorPost;
LOGDIAG1(
"%s: %s thread created.", WhoName[Who], AinWCharName[me]);
if( OptsNoColor )
{
sColorPre = "";
sText = Say[me];
sColorPost = "";
}
else
{
sColorPre = Color[me];
sText = Say[me];
}
while( ThreadState[n] )
{
printf("%s", sColorPre); usleep(10000);
printf("%s: ", AinWCharName[me]); usleep(10000);
printf("%s", sText); usleep(10000);
printf("%s", sColorPost); usleep(10000);
printf("\n");
}
LOGDIAG1(
"%s: %s thread killed.", WhoName[Who], AinWCharName[me]);
}
{
int i;
{
ThreadState[i] = 1;
if( pthread_create(&Thread[i], NULL,
threadmain, &AinWCharId[Who][i]) != 0 )
{
return -1;
}
}
return 0;
}
{
int i;
{
ThreadState[i] = 0;
pthread_join(Thread[i], NULL);
}
}
{
Who = who;
LOGDIAG1(
"%s: creating shared memory mutex.", WhoName[Who]);
if( !OptsNoMutex )
{
{
LOGERROR(
"%s: failed to create mutex.", WhoName[Who]);
}
}
{
return;
}
switch( Who )
{
sleep(3);
break;
sleep(4);
break;
default:
break;
}
if( !OptsNoMutex )
{
}
}
int main(
int argc,
char *argv[])
{
pid_t pid;
{
return 2;
}
switch( (pid = fork()) )
{
case -1:
LOGERROR(
"Failed to fork child process.");
return 8;
case 0:
break;
default:
break;
}
return 0;
}