unix 编程 共享内存总结

1.原理

共享内存是IPC常用的一种形式。

它的原理就是:

一个进程首选调用系统调用shmget向内核申请一块内存。

这时内核就维护了一个全局的共享内存的数据结构。

如果一个进程要使用这块全局的数据结构。要调用shmat这个系统调用。把那块共享内存挂到自己的进程的内存空间。


2.实现细节

第一步:因为大家要共享一个全局的数据区域。就像几个人一块儿约会,前提是要知道这个约会的地点。

UNIX 有三种方法可以让大家知道这个约会地点。

第一种:server进程用一个私有的key创建一个标示符 放到一个众所周知的地方。

第二种:写在代码里面。两个进程的头文件定义这个key

第三种:两个进程约定一个pathname和一个objectID,每个进程调用ftok生成key。


UNIX高级编程的原文:


There are various ways for a client and a server to rendezvous at the same IPC structure.

  1. The server can create a new IPC structure by specifying a key of IPC_PRIVATE and store the returned identifier somewhere (such as a file) for the client to obtain. The key IPC_PRIVATE guarantees that the server creates a new IPC structure. The disadvantage to this technique is that file system operations are required for the server to write the integer identifier to a file, and then for the clients to retrieve this identifier later.

    The IPC_PRIVATE key is also used in a parentchild relationship. The parent creates a new IPC structure specifying IPC_PRIVATE, and the resulting identifier is then available to the child after the fork. The child can pass the identifier to a new program as an argument to one of the exec functions.

  2. The client and the server can agree on a key by defining the key in a common header, for example. The server then creates a new IPC structure specifying this key. The problem with this approach is that it's possible for the key to already be associated with an IPC structure, in which case the get function (msgget, semget, or shmget) returns an error. The server must handle this error, deleting the existing IPC structure, and try to create it again.

  3. The client and the server can agree on a pathname and project ID (the project ID is a character value between 0 and 255) and call the function ftok to convert these two values into a key. This key is then used in step 2. The only service provided by ftok is a way of generating a key from a pathname and project ID.

#include <sys/ipc.h>

key_t ftok(const char *path, int id);

Returns: key if OK, (key_t)-1 on error


第二部:创建共享内存


int shmget(key_t key, size_t size, int flag);

一个参数是 我们约定的KEY。 第二个参数指定共享内存的大学。第三个参数共享内存标识符。


第三部:挂载共享内存到自己的进程空间

void *shmat(int shmid, const void *addr, int flag);

第一个参数就是第二部返回的id。其它两个参数一般用0就ok了。


详情可以查阅 UNIX高级编程 第二版15章 第九节。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值