Help about shared memory
Andy Johnson
ajohnson at killer.UUCP
Fri Feb 19 15:12:05 AEST 1988
In article <1739 at phoenix.Princeton.EDU>, asjoshi at phoenix.Princeton.EDU (Amit S. Joshi) writes:
> I wanted to share some data between two processes. I looked up the
> manual and found something called "shared memory". Could somebody tell
> me waht that is and how do I use it ?
I wrote a multi-user bbs and wanted to use shared memory to facilitate
communications between users, specifically for "chat". I wrote this
simple program to test the shared memory facilities of Microport. It
worked find and I have been using shared memory for over a year without
a problem. Hope this helps.
Andy Johnson
{inhp4!codas!}!killer!ajohnson
---------------
CUT HERE.......
---------------
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define MEMORY 0x62627321 /* string = "bbs!" */
#define MAX_PRG 5
#define ERROR -1
typedef struct mpstr
{
unsigned char lst_in;
unsigned char in_recd;
unsigned char lst_ot;
unsigned char ot_recd;
unsigned char whoami[30];
unsigned char who_chat;
unsigned char on_line;
} MEMPRG;
typedef struct memstr
{
int wrtflg;
MEMPRG memprg[MAX_PRG];
} MEMSTR;
char name[80] ="THIS IS A STRING";
main(argc, argv)
int argc;
char **argv[];
{
MEMSTR *memptr;
char *memget();
int pgmno;
pgmno = 0;
if (argc >1)
pgmno = 1;
printf("\nProgram = %d\n",pgmno);
printf("\nName = %s\n",name);
memptr = (MEMSTR*)memget();
memptr->memprg[pgmno].on_line = 1;
/* strcpy(memptr->memprg[pgmno].whoami,"USER XXX");*/
printf("\nput it into memory!\n");
printf("\nid=%s\n",memptr->memprg[0].whoami);
printf("\nid=%s\n",memptr->memprg[1].whoami);
printf("\nName = %s\n",name);
remmem(memptr);
printf("\nAll done!\n");
exit(0);
}
char *memget()
{
char *shmat();
char *memadr;
int mid;
mid = shmget(MEMORY,sizeof(MEMSTR),(IPC_CREAT | 0666));
if (mid == ERROR)
{
printf("\nError getting memory errno = %d\n",errno);
exit(1);
}
printf("\nmid = %d\n",mid);
memadr = shmat(mid,(char*)0,0);
if (memadr == -1L)
{
printf("\nAttach failed %d\n",errno);
exit(1);
}
printf("\nMemory attached at %lx\n",memadr);
return(memadr);
}
remmem(memadr)
char *memadr;
{
int result;
result = shmdt(memadr);
if (result == ERROR)
{
printf("\nCan't detach memory error %d\n",errno);
exit(1);
}
}
More information about the Comp.unix.questions
mailing list