共用記憶體 進程通訊

來源:互聯網
上載者:User

參考地址:http://www.ibm.com/developerworks/cn/linux/l-ipc/part5/index1.html?ca=drs-

main.c

/*-------------map_normalfile1.c-----------*/
#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
typedef struct{
char name[4];
int age;
}people;
main(int argc, char** argv) // map a normal file as shared mem:
{
int fd,i;
people *p_map;
char temp;

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 );
temp = 'a';
for(i=0; i<10; i++)
{
temp += 1;
memcpy( ( *(p_map+i) ).name, &temp,2 );
( *(p_map+i) ).age = 20+i;
}
printf(" initialize over \n ");
sleep(10);
munmap( p_map, sizeof(people)*10 );
printf( "umap ok \n" );
}

 

client.c

/*-------------map_normalfile2.c-----------*/
#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
typedef struct{
char name[4];
int age;
}people;
main(int argc, char** argv) // map a normal file as shared mem:
{
int fd,i;
people *p_map;
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);
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 );
}

 

Makefile

all:main
main:
gcc -g -Wall -O0 main.c -o main

client:
gcc -g -Wall -O0 client.c -o client

clean:
rm *.o main client

 

分別把兩個程式編譯成可執行檔map_normalfile1和map_normalfile2後,在一個終端上先運行./map_normalfile2 /tmp/test_shm,程式輸出結果如下:

initialize overumap ok

 

在map_normalfile1輸出initialize over 之後,輸出umap ok之前,在另一個終端上運行map_normalfile2 /tmp/test_shm,將會產生如下輸出(為了節省空間的,輸出結果為稍作整理後的結果):

name: bage 20;name: cage 21;name: dage 22;name: eage 23;name: fage 24;name: gage 25;name: hage 26;name: Iage 27;name: jage 28;name: kage 29;

 

在map_normalfile1 輸出umap ok後,運行map_normalfile2則輸出如下結果:

name: bage 20;name: cage 21;name: dage 22;name: eage 23;name: fage 24;name:age 0;name:age 0;name:age 0;name:age 0;name:age 0;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.