Is there an easy way to copy a variable in the heap into shared memory

时光怂恿深爱的人放手 提交于 2019-12-11 20:57:15

问题


I have a couple of structs with pointers to one another allocated on the heap. I'm converting a multi-threaded program to a multi-process program so I have to make those structs on the heap into shared memory. So far, I've run into nothing but problems on top of problems. MY TA suggested I use memcpy, but I'm not sure that's going to work. Is there any way to convert a set of structs on the heap into shared memory?

Structs I'm using:

 struct SharedData {
    int da;
    int         isopen;
    int     refcount;   // reference count:  number of threads using this object
    unsigned int    front;      // subscript of front of queue
    unsigned int    count;      // number of chars in queue
    unsigned int    bufsize;
    pthread_cond_t buffer_full;
    pthread_cond_t buffer_empty;
    pthread_mutex_t mtex;
    fifo_t* queue;
    sem_t       empty_count;

    sem_t       full_count;
    sem_t       use_queue;  // mutual exclusion
};

struct OverSharedData{
    struct SharedData ** rep;
    int rop;
};

I malloc'd OverSharedData , the SharedData structs, and the fifo_t queue, along with multiple char pointers later on. Do they all have to be declared as shared memory?


回答1:


In the way malloc() request memory from heap, there are system calls (for e.g. shmget()) to request/create shared memory segment. If your request is successful, you can copy whatever you like over there. (Yes, you can use memcpy.) But remember to be careful about pointers, a pointer valid for one process, kept in its shared memory, is not necessarily valid for another process using that shared memory segment.

The shared memory is accessible to all processes for reading and/or writing. If multiple processes are reading/writing to a shared memory segment, then, needless to say, some synchronization techniques (for e.g. semaphore) need to be applied.

Please read up on shared memory. An excellent source is "The Linux Programming Interface" by Michael Kerrisk.

Reference:

  • http://man7.org/linux/man-pages/man7/shm_overview.7.html
  • http://man7.org/linux/man-pages/man2/shmget.2.html
  • http://www.amazon.com/The-Linux-Programming-Interface-Handbook/dp/1593272200


来源:https://stackoverflow.com/questions/23145802/is-there-an-easy-way-to-copy-a-variable-in-the-heap-into-shared-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!