main_r.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SHM_SIZE 100
int main(void)
{
int shmid;
char buff[SHM_SIZE];
void *shmadr;
int ret;
shmid = shmget((key_t)12345, SHM_SIZE, 0666|IPC_CREAT);
if (shmid == -1) {
printf("creat share memory failed!
");
exit(1);
}
shmadr = shmat(shmid, 0, 0);
if (shmadr == (void*)-1) {
printf("shmat failed!
");
exit(1);
}
memset(buff, 0, sizeof(buff));
memcpy(buff, (char*)shmadr, sizeof(buff));
printf("get: %s
", buff);
ret = shmdt(shmadr);
if (ret == -1) {
printf("shmdt failed!
");
exit(1);
}
return 0;
}
main_w.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SHM_SIZE 100
int main(void)
{
int shmid;
char buff[SHM_SIZE];
void *shmadr;
int ret;
shmid = shmget((key_t)12345, SHM_SIZE, 0666|IPC_CREAT);
if (shmid == -1) {
printf("creat share memory failed!
");
exit(1);
}
shmadr = shmat(shmid, 0, 0);
if (shmadr == (void*)-1) {
printf("shmat failed!
");
exit(1);
}
strcpy(buff, "hello word!");
memcpy((char*)shmadr, buff, strlen(buff)+1);
ret = shmdt(shmadr);
if (ret == -1) {
printf("shmdt failed!
");
exit(1);
}
return 0;
}