进程通信-共享内存-mmap()-code2

/*-------------map_normalfile2.c-----------*/ 

#include <sys/types.h> 
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h> 
#include <sys/mman.h> 

typedef struct { 
    char name[20]; 
    int  age; 
}people;

int main(int argc, char** argv)	
{ 
    int fd,i; 
    people *p_map;
    people *p_map_seg1;
    people *p_map_seg2;
    people *p_map_seg3;
    char temp[20]={0};
    
    fd=open( "map_normalfile.in", O_CREAT|O_RDWR, 00777 ); 
    p_map = (people*)mmap( NULL,sizeof(people)*10*3,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0 );
    p_map_seg1 = p_map;
    p_map_seg2 = p_map+10;
    p_map_seg3 = p_map+20;
    close( fd );
    
    printf("p_map=0x%x\n", p_map); //在各个进程中映射同一文件, mmap返回的内存映像地址相同

    printf("========Write Seg2===================\n");
    for(i=0; i<10; i++) 
    { 
        sprintf(temp, "peple_2%02d", i);
        memcpy( ( *(p_map_seg2+i) ).name, temp, strlen(temp)+1); 
        ( *(p_map_seg2+i) ).age = 20+i; 
        printf( "name:%s age:%d;\n",(*(p_map_seg2+i)).name, (*(p_map_seg2+i)).age ); 
        sleep(1);
    } 
    printf(" initialize seg2 over \n "); 
    sleep(10); 
    
     printf("=========All Data==================\n");
    for(i = 0;i<30;i++)
    { 
        printf( "name=%s age=%d;\n",(*(p_map+i)).name, (*(p_map+i)).age ); 
    } 
    sleep(30); 
    munmap( p_map, sizeof(people)*10*3 );
    printf( "umap ok \n" ); 
    return 0;
}


你可能感兴趣的:(struct,null)