#include
#include
#include
#include
#include
#include
#include
#define SEGSIZE 100
void writeshm(int shmid, char *segptr, char *text)
{
strcpy(segptr, text);
printf("Write Done...\n");
}
void readshm(int shmid, char *segptr)
{
printf("Read from segptr: %s\n", segptr);
}
void removeshm(int shmid)
{
shmctl(shmid, IPC_RMID, 0);
printf("Shared memory segment marked for deletion\n");
}
int main(int argc, char *argv[])
{
key_t key;
int shmid;
char *segptr;
/* Create unique key via call to ftok() */
key = ftok(".", 'S');
/* Open the shared memory segment - create if necessary */
if((shmid = shmget(key, SEGSIZE, IPC_CREAT|IPC_EXCL|0666)) == -1)
{
printf("Shared memory segment exists - opening as client\n");
/* Segment probably already exists - try as a client */
if((shmid = shmget(key, SEGSIZE, 0)) == -1)
{
perror("shmget");
exit(1);
}
}
else
{
printf("Creating new shared memory segment\n");
}
/* Attach (map) the shared memory segment into the current process */
if((segptr = (char *)shmat(shmid, 0, 0)) == (char *)-1)
{
perror("shmat");
exit(1);
}
//char mywords[] = "hello!";
//writeshm(shmid, segptr, mywords);
readshm(shmid, segptr);
removeshm(shmid);
return 0;
}
原文资料:
http://www.tldp.org/LDP/lpg/node65.html