System V IPC message queues, semaphores, and shared memory

System V IPC

     System V IPC指的是AT&T在System V.2发行版中引入的三种进程间通信工具:
     (1)信号量,用来管理对共享资源的访问
     (2)共享内存,用来高效地实现进程间的数据共享
     (3)消息队列,用来实现进程间数据的传递。
     我们把这三种工具统称为System V IPC的对象,每个对象都具有一个唯一的IPC标识符(identifier)。要保证不同的进程能够获取同一个IPC对象,
     必须提供一个IPC关键字(IPC key),内核负责把IPC关键字转换成IPC标识符。

ftok函数:

The ftok() function uses the identity of the file named by the given pathname (which must refer to an existing, accessible file) and the least significant 8 bits of proj_id(which must be nonzero) to generate a key_t type System V IPC key, suitable for use with msgget(2),semget(2), orshmget(2).

#include sys/types.h #include sys/ipc.h

头文件<sys/types.h>把key_t定义为一个整数,通常是一个至少32位的整数,由ftok函数赋予的。函数ftok把一个已存的路径和一个整数标识符转换成一个key_t值,称为IPC键。

key_t ftok(const char *pathname, int proj_id);

pathname就是你指定的文件名(该文件必须是存在而且可以访问的); 是将文件的索引节点号(inode)取出(可用:ls -i 查看)

proj_id 是子序号,虽然为int,但是只有8个比特被使用(0-255); 同一个pathname下最多可以有256个不同的key_t

struct stat {
    dev_t     st_dev;     /* ID of device containing file */
    ino_t     st_ino;     /* inode number */
    mode_t    st_mode;    /* protection */
    nlink_t   st_nlink;   /* number of hard links */
    uid_t     st_uid;     /* user ID of owner */
    gid_t     st_gid;     /* group ID of owner */
    dev_t     st_rdev;    /* device ID (if special file) */
    off_t     st_size;    /* total size, in bytes */
    blksize_t st_blksize; /* blocksize for file system I/O */
    blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
    time_t    st_atime;   /* time of last access */
    time_t    st_mtime;   /* time of last modification */
    time_t    st_ctime;   /* time of last status change */
};

key_t IPC_key = 0X Lower8Bits(proj_id) Lower8Bits(st_dev) Lower16Bits(st_ino)

e.g.

key_t IPC_key = 0;
if ((IPC_key = ftok(".", 0x01)) == -1) {
    perror("ftok() error");
    exit(EXIR_FAILURE);
}

当成功执行的时候,一个key_t值将会被返回,否则 -1 被返回

消息队列 (message queues)

信号量 (semaphores)

共享内存 (shared memory)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值