Shared memory example
Richard Fox
rfox at amelia.nas.nasa.gov
Fri May 13 07:11:42 AEST 1988
Thanks for all of the responses to my question regarding shared memory.
Many people asked for me to send them a copy of an example that I received.
Instead of sending to all I thought I would just post a very simple
program derived from a more complex program. If there are still comments
regarding shared memory please send them otherwise thanks again for
the response.
-------------------------------------------------------------
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
extern int errno;
#define SHMKEY 75
#define K 1024
int shmid;
char *addr1,*addr2;
main(argc,argv)
int argc;
char **argv;
{
int i, *pint;
key_t key;
extern char *shmat();
extern cleanup();
key = IPC_PRIVATE;
shmid = shmget( key, 1*K,0777|IPC_CREAT);
printf("shmid %d errno=%d\n",shmid,errno);
addr1 = shmat(shmid,0,0);
printf("addr1 0x%x\n",addr1);
for(i=0; i<20; i++)
signal(i,cleanup);
addr1[K-1]=0;
if(fork()) {
writer();
printf("RETURN WRITER\n");
} else
{
reader();
printf("RETURN READER\n");
kill(0,9);
}
pause();
}
cleanup()
{
shmctl(shmid, IPC_RMID,0);
printf("In clean up\n");
exit(0);
}
writer()
{
int i;
printf("In writer\n");
for(i=0;i<K;i++){
/*printf("addr1[%d] = %d\n",i,addr1[i]);*/
addr1[i]=5;
}
while(addr1[K-1]!=0);
}
reader()
{
int i;
printf("In reader\n");
while(addr1[K-1]==0);
printf("going....reader\n");
for(i=0;i<K;i++)
printf(" addr1[%d]=%d\n",i,addr1[i]);
addr1[K-1]=0;
}
More information about the Comp.unix.wizards
mailing list