shm_open:Mac和Linux之间的差异

时间:2016-02-09 21:06:56

标签: c linux macos shared-memory

我在共享内存中有一个队列。它适用于Linux(内核4.3.4),但不适用于Mac OS X.Mac OS X如何处理共享内存与linux的工作方式有何不同,这可以解释一下?

我通过以下方式获取共享内存:

int sh_fd = shm_open(shmName, O_RDWR | O_CREAT, 
        S_IROTH | S_IWOTH // others hav read/write permission
        | S_IRUSR | S_IWUSR // I have read/write permission
        );

// bring the shared memory to the desired size
ftruncate(sh_fd, getpagesize());

队列也非常简单。这是基本结构:

typedef struct {
// this is to check whether the queue is initialized.
// on linux, this will be 0 initially
bool isInitialized;
// mutex to protect concurrent access
pthread_mutex_t access;
// condition for the reader, readers should wait here
pthread_cond_t reader;
// condition for the writer, writers should wait here
pthread_cond_t writer;
// whether the queue can still be used.
bool isOpen;
// maximum capacity of the queue.
int32_t capacity;
// current position of the reader and number of items.
int32_t readPos, items;

// entries in the queue. The array actually is longer, which means it uses the space behind the struct.
entry entries[1];
} shared_queue;

基本上每个想要访问的人都获取互斥锁,readPos指示应该读取下一个值的位置(之后增加readPos),(readPos + items)%capacity是新项目的位置。唯一有点花哨的技巧是isInitialized字节。如果ftruncate之前的长度为0,则ftruncate用零填充共享内存,所以我依赖isInitiualized在新的共享内存页面上为零,并在初始化结构时立即写入1。

正如我所说,它适用于Linux,因此我认为这不是一个简单的实现错误。 Mac和Linux上的shm_open之间有什么微妙的区别我可能不知道吗?我看到的错误看起来像读者试图从空队列中读取,因此,pthread互斥/条件可能不适用于Mac上的共享内存?

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:1)

您必须在互斥锁和条件变量上设置PTHREAD_PROCESS_SHARED

所以对于互斥锁:

pthread_mutexattr_t mutex_attr;
pthread_mutex_t     the_mutex;

pthread_mutexattr_init(&mutex_attr);
pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_SHARED);
pthread_mutexattr(&the_mutex, &mutex_attr);

基本上与条件变量的步骤相同,但将mutexattr替换为condattr

如果pthread_*attr_setpshared功能不存在或返回错误,则您的平台可能不支持此功能。

为安全起见,如果支持,您可能需要设置PTHREAD_MUTEX_ROBUST。如果进程在保持锁定时退出,这将防止互斥锁上的死锁(虽然不保证队列一致性)。

编辑:另外要注意的是,初始化布尔值""旗帜本身就是一个不充分的计划。您需要的不仅仅是确保只有一个进程可以初始化结构。至少你需要这样做:

// O_EXCL means this fails if not the first one here
fd = shm_open(name, otherFlags | O_CREAT | O_EXCL );  
if( fd != -1 )
{
   // initialize here

   // Notify everybody the mutex has been initialized.
}
else
{
    fd = shm_open(name, otherFlags ); // NO O_CREAT

    // magically somehow wait until queue is initialized.
}

您确定需要自己推出自己的队列吗? POSIX消息队列(请参阅mq_open手册页)是否可以完成这项工作?如果没有,那么许多消息传递中间件解决方案之一呢?

更新2016年2月10日:可能基于mkfifo的解决方案

在共享内存中实现自己的队列的另一种方法是使用mkfifo提供的名为FIFO的操作系统。 FIFO和命名管道之间的关键区别在于,您可以同时拥有多个读取器和写入器。

A" catch"对此,读者在最后一个作者退出时看到文件结尾,所以如果你想让读者无限期地去,你可能需要打开一个虚拟的写句柄。

FIFO在命令行上非常容易使用,如下所示:

reader.sh

mkfifo my_queue
cat my_queue

write.sh

echo "hello world" > my_queue

或者在C中稍稍努力:

reader.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>

int main(int argc, char**argv)
{
  FILE * fifo;
  FILE * wfifo;
  int res;
  char buf[1024];
  char * linePtr;

  /* Try to create the queue.  This may belong on reader or writer side
   * depending on your setup. */
  if( 0 !=  mkfifo("work_queue", S_IRUSR | S_IWUSR ) )
  {
    if( errno != EEXIST )
    {
      perror("mkfifo:");
      return -1;
    }
  }

  /* Get a read handle to the queue */
  fifo = fopen("work_queue", "r"); 

  /* Get a write handle to the queue */
  wfifo = fopen("work_queue", "w"); 
  if( !fifo )
  {
    perror("fopen: " );
    return -1;
  }

  while(1)
  {
    /* pull a single message from the queue at a time */
    linePtr = fgets(buf, sizeof(buf), fifo);
    if( linePtr )
    {
      fprintf(stdout, "new command=%s\n", linePtr);
    }
    else
    {
      break;
    }
  } 

  return 0;
}

writer.c

#include <stdio.h>
#include <unistd.h>
int main(int argc, char**argv)
{
  FILE * pipe = fopen("work_queue", "w");
  unsigned int job = 0;
  int my_pid = getpid(); 
  while(1)
  {
    /* Write one 'entry' to the queue */
    fprintf(pipe, "job %u from %d\n", ++job, my_pid);
  }
}
相关问题