I have two processes and i want to share a linked list between them. One of the processes is just going to read the list while other process is going to modify the list ( add/delete entries). Can you tell me how to achieve it?
Let me add more details to it the language is C and the platform is Linux. It seems that shared memory is one approach but i do not know how to implement it.
IF any one can tell me the way of achieving it then it will be of great help to me.
I have one idea as mentioned below: Can i do something like this where i create a segment of shared memory of size of the node. Then i simply deal with malloc?What i mean is i will create the shared memory with help of shmget(key, SHMSZ, IPC_CREAT|0666)where SHMSZ will be of size of struct node. So i only share head of list between two process. The first entry in list will have all values of 0 except link entry which will point to next entry in list and that entry is created with help of malloc since In my application since other process is going to read only while one process is going to add/delete entries in list.
I got one reply which tells me that i can not use malloc. I do not know why i can not use malloc. Could you please tell me why i can not use malloc?
Below is my code for the above mentioned purpose which i have been trying but getting segmentation fault.
struct node
{
int val;
struct node* next;
};
void append(struct node *q,int val);
main()
{
key_t key = 5678;
int shmid;
struct node *head;
if ((shmid = shmget(key, sizeof(struct node), IPC_CREAT | 0666)) < 0) {
perror("shmget");
exit(1);
};
head = struct node*(shmat(shmid, (void *) 0, 0));
head->val = 0;
head->next= 0;
append(head,2);
append(head,5);
append(head,6);
exit(0);
}
void append(struct node *q,int val)
{
struct node *temp1,*temp2;
if (q->next == 0)
{
temp1=malloc(sizeof(struct node));
temp1->val = val;
temp1->next = 0;
q->next = temp1;
}
else
{
temp2=malloc(sizeof(struct node));
temp2->val = val;
temp1 = q->next;
while(1)
{
if (temp1 == 0)
{
temp1=temp2;
break;
}
else
temp1=temp1->next;
}
}
return;
}