此代码来自...[反正不是自己写的]
nginx使用了mmap()来操作共享内存,但是没有使用文件指针,对于不使用文件指针的第二个进程怎么获取内存
-
/**************************************************************************************/
-
/*简介:mmap_write共享内存,写操作子程序 */
-
/*************************************************************************************/
-
#include <sys/mman.h>
-
#include <sys/types.h>
-
#include <fcntl.h>
-
#include <unistd.h>
-
#include <stdlib.h>
-
#include <string.h>
-
#include <stdio.h>
-
-
typedef struct
-
{
-
char name[4];
-
int age;
-
}people;
-
-
int main(int argc, char** argv)
-
{
-
int fd,i;
-
people *p_map;
-
char name[4];
-
if (argc != 2)
-
{
-
perror("usage: mmap_write ");
-
return 1;
-
}
-
-
fd=open(argv[1],O_CREAT|O_RDWR|O_TRUNC,00777);
-
lseek(fd,sizeof(people)*5-1,SEEK_SET);
-
write(fd,"",1);
-
-
p_map = (people*) mmap( NULL,sizeof(people)*10,\
-
PROT_READ|PROT_WRITE,MAP_SHARED,fd,0 );
-
close( fd );
-
name[0] = 'a';
-
name[1] = '\0';
-
for(i=0; i<10; i++)
-
{
-
name[0] ++;
-
memcpy( ( *(p_map+i) ).name, &name,sizeof(name) );
-
( *(p_map+i) ).age = 20+i;
-
}
-
printf(" initialize over \n ");
-
sleep(10);
-
-
munmap( p_map, sizeof(people)*10 );
-
printf( "umap ok \n" );
-
return 0;
-
}
-
/**************************************************************************************/
-
/*简介:mmap_read共享内存,读操作子程序 */
-
/*************************************************************************************/
-
#include <sys/mman.h>
-
#include <sys/types.h>
-
#include <fcntl.h>
-
#include <unistd.h>
-
#include <stdio.h>
-
#include <stdlib.h>
-
-
typedef struct
-
{
-
char name[4];
-
int age;
-
}people;
-
-
int main(int argc, char** argv)
-
{
-
int fd,i;
-
people *p_map;
-
if (argc != 2)
-
{
-
perror("usage: mmap_read ");
-
return 1;
-
}
-
fd=open( argv[1],O_CREAT|O_RDWR,00777 );
-
p_map = (people*)mmap(NULL,sizeof(people)*10,\
-
PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
-
close(fd);
-
for(i = 0;i<10;i++)
-
{
-
printf( "name: %s age %d;\n",(*(p_map+i)).name, (*(p_map+i)).age );
-
}
-
munmap( p_map,sizeof(people)*10 );
-
return 0;
-
}
阅读(1298) | 评论(0) | 转发(0) |