现在的位置: 首页 > 综合 > 正文

共享内存——The Shared memory

2017年12月15日 ⁄ 综合 ⁄ 共 1061字 ⁄ 字号 评论关闭

// share  the memory space
// 出于多个进程之间通信考虑的
// 每个IPC的object 通过键,进程识别所用的object

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/shm.h>

#define MEMSIZE 2048

int main()
{
 int shmid;
 pid_t pid;
 char *ptr;
//  建立共享内存()键值key参数为IPC_PRIVATE/0 创建一块新的共享内存。
// void *shmat(int shmid, const void *shmaddr, int shmflg);
//  shmflg 文件标志,
//  IPC_CREAT (共享内存)无则创建,有则打开
//  IPC_EXCEL  只有共享内存不存在时,才创建,否则出错。
//  IPC_CREAT|IPC_EXCEL 确保是新创建的,而不是打开已有的共享内存。
  shmid = shmget(IPC_PRIVATE,MEMSIZE,0600);
//
 if(shmid < 0)
 {
  perror("shmget()");
  exit(1);
 }

 pid = fork();
 if(pid < 0)
 {
  perror("fork()");
  exit(1);
 } 

 if(pid == 0)  // child write
 {
  // 允许本进程使用某块共享内存
  ptr = shmat(shmid,NULL,0);
  if(ptr == (void *) -1)
  {
   perror("shmat()");
   exit(1);
  }
  strcpy(ptr,"hello");
  //禁止本进程使用这块空间。
  shmdt(ptr);
  exit(0);
 }
 else   // parent read
 {
  wait(NULL);
  ptr = shmat(shmid,NULL,0);
        if(ptr == (void *) -1)
        {
            perror("shmat()");
            exit(1);
        }
  puts(ptr);
        shmdt(ptr);
  //
  //IPC_RMID  删除这块共享内存。
  //IPC_SET 改变共享内存的状态
  //IPC_STAT 得到共享内存的状态
  shmctl(shmid,IPC_RMID,NULL);
     exit(0);
 }

}

 

 

抱歉!评论已关闭.