【问题标题】:Why and when one should use IPC_NEW to create semaphore?为什么以及何时应该使用 IPC_NEW 创建信号量?
【发布时间】:2014-10-24 07:02:29
【问题描述】:

我们可以通过两种方式创建信号量。
1.

 static unsigned int state = 1 ;
 key_t h=ftok(".", state++);
 int sem_id=semget(h, no_of_sems, IPC_CREAT|0666);


2.

 int sem_id =semget(IPC_NEW,no_of_sems,0666|IPC_CREAT);

正如Linux手册http://man7.org/linux/man-pages/man2/shmget.2.html中提到的那样

IPC_PRIVATE 不是标志字段,而是 key_t 类型。如果这个特别 value 用于 key,系统调用忽略除最少之外的所有 显着 9 位 shmflg 并创建一个新的共享内存段。

我没有得到手册所说的内容。有人可以解释更多吗?
第一种方法比第二种方法的优缺点是什么?

Edit:
IPC_PRIVATE => IPC_NEW 

【问题讨论】:

标签: c++ c linux ipc semaphore


【解决方案1】:

首先你应该观察BUG

   The name choice IPC_PRIVATE was perhaps unfortunate, IPC_NEW would
   more clearly show its function.

好的。我只是解释了我对shmget的了解

查看shmget的描述

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

DESCRIPTION
   shmget()  returns  the identifier of the System V shared memory segment
   associated with the value of the argument key. A  new  shared  memory
   segment,  with size equal to the value of size rounded up to a multiple
   of PAGE_SIZE, is created if key has the value IPC_PRIVATE or key  isn't
   IPC_PRIVATE,  no shared memory segment corresponding to key exists, and
   IPC_CREAT is specified in shmflg.

ipc.h 文件中IPC_CREAT 被定义为类似宏

 /* resource get request flags */
 #define IPC_CREAT  00001000   /* create if key is nonexistent */
 #define IPC_EXCL   00002000   /* fail if key exists */
 #define IPC_NOWAIT 00004000   /* return error on wait */

如果单独使用 IPC_CREAT,则 shmget() 要么返回新创建的段的段标识符,要么返回具有相同键值的段的标识符。如果 IPC_EXCL 与 IPC_CREAT 一起使用,则创建一个新段,或者如果该段存在,则调用失败并返回 -1。 IPC_EXCL 本身没有用,但是当与 IPC_CREAT 结合使用时,它可以用作保证不打开现有段进行访问的工具。

如果满足以下条件之一,则为 key 创建至少 size 个字节的共享内存标识符和关联的数据结构和共享内存段:

   o  The key argument is equal to IPC_PRIVATE.

   o  The key argument does not already have a shared  memory
      identifier  associated  with it, and (shmflg&IPC_CREAT)
      is true.

【讨论】:

  • 您是对的,您获取了所有信息。为什么要使用第二个选项?
  • IPC_CREAT:如果不存在具有指定键的信号量集,则创建一个新集。
  • 第一种方法也在做同样的事情?
猜你喜欢
  • 1970-01-01
  • 2010-12-07
  • 1970-01-01
  • 2014-05-22
  • 2015-03-25
  • 1970-01-01
  • 2023-03-08
  • 2013-01-29
  • 1970-01-01
相关资源
最近更新 更多