dhilst

shared memory hello world improved by signals

/* file: shared-write.c
compiling: gcc -o shared-write shared-write.c */
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <stdio.h>
#include <sys/shm.h>


/* Make this global, so visible inside handler */
static char * shared_memory;
static int segment_id;


/* SIGNAL handler
detach and deallocate */
void
handler (int signumber)
{
shmdt (shared_memory);
shmctl (segment_id, IPC_RMID, 0);
exit (0);
}

int
main (void)
{
key_t key = 2525;
int segment_size = 0x6400;
/* Needed for signal handler */
struct sigaction sa;
/* install signal handler */
sa.sa_handler = & handler;
sigaction (SIGUSR1, &sa, NULL);

/* get a shareable segment */
segment_id = shmget (key, segment_size, IPC_CREAT | 0666);
/* attach it with shared_memory */
shared_memory = shmat (segment_id, NULL, 0);
/* write into */
sprintf (shared_memory, "0%d,Hello World", getpid());

/* wait for signal */
while (1)
sleep (1);

/* the program must exit through handler */
return -1;
}
/* file: shared-read.c
compiling: gcc -o shared-read shared-read.c */
#include <string.h>
#include <stdio.h>
#include <sys/shm.h>
#include <signal.h>
#include <sys/types.h>

int
main (void)
{
int segment_id;
pid_t pid_of_brother;
key_t key = 2525;
char * shared_memory, string;
int segment_size = 0x6400;
char * ptr1, * ptr2, * ptr3;

/* get the shared segment, using the same key */
segment_id = shmget (key, segment_size, 0666);
/* attaching */
shared_memory = shmat (segment_id, NULL, 0);
/* There is pid of the other process and a string
split by a comma. Take the 2 values by walk
through pointers */
ptr1 = strchr (shared_memory, ',');
/* here I got the pid. If the pid is 4 numbers then
one 0 is taken at begining of pid */
ptr2 = ptr1 - 5;
/* and here is string */
ptr3 = ptr1 + 1;
/* conver pid to pid type */
pid_of_brother = (pid_t) atoi (ptr2);
/* write string to stdout */
printf ("%s\n", ptr3);
/* send SIGUSR1 signal to other process
saying HEY I FINISH
so it can detach and deallocate the
shared memory */
kill (pid_of_brother, SIGUSR1);

return 0;
}
running:
$ ./shared-write &
[1] 2026
$ ./shared-read
Hello World
[1]+ Done ./shared-write