在写股票软件过程中, 我希望把读取数据和显示数据的过程分离,他们的数据交换通过一个共享的链表来解决。
通过shmget,可以获得一块共享的内存,但通常的情况下,一般申请的都是连续的空间,也就是说,我需要把数据存成一个数组,放在共享中。这个不是我的初衷。
最初,我希望能只共享一个头指针,以为这样就可以直接共享链表了。但是结果是不可行的。
经过一番实验和google,最终找到了解决办法。
关键点:
1.通常每个节点node,其中的next域存储的是*node, 即指向下个节点的指针。在这里,我们不能使用*node,否则读取程序是没法正确读取的。具体原因不清楚,但是经过实践证明,不可行。所以我们使用一个节点内存对应的shmid来当作先个节点的指示符,他的类型是int.
2.由于共享的是整个链表,所以每次为新节点开辟内存时,不能使用malloc,而应该使用shmget. malloc是进程相关的,只有开辟内存的进程才有权限读取内容。
* Filename: writer.c
*
* Description: show create linked list in share memory
*
* Version: 1.0
* Created: 08/20/2012 09:55:21 PM
* Revision: none
* Compiler: gcc
*
* Author: [email protected]
* Organization:
*
* */
#include
#include
#include
#include
//The memory id for the head pointer
#define KEY 5566
//we store the memory id (shmid) as the next, instead of a pointer.
//if you use the *node as next, you will not be able to read it in other thread. I do not know why
typedef struct node{