#include "apue.h"//write
int main()
{
int shm_id;
char *ptr = NULL;
char buf[100];
shm_id = shm_open("/shm.1234", O_RDWR, 0);
if(shm_id < 0)
{
perror("**shm_open");
exit(1);
}
ptr = mmap(NULL,
100,
PROT_READ|PROT_WRITE,
MAP_SHARED,
shm_id, 0);
if(ptr == NULL)
{
perror("mmap");
goto ERR;
}
#if 0
int i=0;
do
{
*ptr = buf[i];
ptr++;
i++;
}while(buf[i-1] != '\0');
#endif
fgets(ptr, 100, stdin);
//munmap(ptr, 50);
ERR:
close(shm_id);
}
#include "apue.h"//创建
int main()
{
int shm_id=0;
int ret;
shm_unlink("./shm.1234");
perror("shm_unlink");
shm_id = shm_open("/shm.1234", O_CREAT|O_RDWR, 0766);
if(shm_id < 0)
{
perror("shm_open");
exit(1);
}
printf("shm_id=%d\n", shm_id);
ret = ftruncate(shm_id, 100);
if(ret == -1)
{
perror("ftruncate");
}
close(shm_id);
}
#include "apue.h"//读取
int main()
{
int shm_id;
char *ptr = NULL;
shm_id = shm_open("/shm.1234", O_RDONLY, 0);
if(shm_id < 0)
{
perror("shm_open");
exit(1);
}
ptr = mmap(NULL, 100, PROT_READ, MAP_SHARED, shm_id, 0);
if(ptr == NULL)
{
perror("mmap");
goto ERR;
}
printf("ptr=%s\n", ptr);
ERR:
close(shm_id);
}