공유 메모리 프로 세 스 통신
                                            
 5517 단어  공유 메모리
                    
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 
 ");
  sleep(10);
  munmap( p_map, sizeof(people)*10 );
  printf( "umap ok 
" );
}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;
",(*(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 로 컴 파일 합 니 다.normalfile 1 과 mapnormalfile 2 후 한 터미널 에서 먼저 실행 합 니 다./mapnormalfile2 /tmp/test_shm,프로그램 출력 결 과 는 다음 과 같 습 니 다.
initialize over
umap ok
맵normalfile 1 에서 initialize over 를 출력 한 후 umap ok 을 출력 하기 전에 다른 터미널 에서 map 를 실행 합 니 다.normalfile2 /tmp/test_shm,다음 과 같은 출력 이 발생 합 니 다(공간 을 절약 하기 위해 출력 결 과 는 약간 정 리 된 결과 입 니 다).
name: b	age 20;	name: c	age 21;	name: d	age 22;	name: e	age 23;	name: f	age 24;
name: g	age 25;	name: h	age 26;	name: I	age 27;	name: j	age 28;	name: k	age 29;
맵normalfile 1 출력 umap ok 후 map 실행normalfile 2 는 다음 과 같은 결 과 를 출력 합 니 다.
name: b	age 20;	name: c	age 21;	name: d	age 22;	name: e	age 23;	name: f	age 24;
name:	age 0;	name:	age 0;	name:	age 0;	name:	age 0;	name:	age 0;이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
프로 세 스 간 공유 메모 리 를 해결 합 니 다. 프로 세 스 가 이상 하 게 종료 되 어 잠 금 문제 가 발생 했 습 니 다.모든 fpm - phop 의 읽 기 프로 세 스 가 자 물 쇠 를 차지 하지 않 은 것 을 발 견 했 습 니 다. 이 는 읽 기 프로 세 스 가 자 물 쇠 를 얻 은 후에 풀 지 못 하고 끊 었 다 는 것 을 의미 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.