I have two processes and I want to share a linked list between them. One of the processes is just about to read the list, while the other process will change the list (add / remove entries). Can you tell me how to achieve it?
Let me add more information that the language is C and the platform is Linux. Shared memory seems to be one approach, but I don't know how to implement it.
IF anyone can tell me how to achieve it, then it will be very useful for me.
I have one idea, as follows: Can I do something like this when I create a node-sized shared memory segment. Then I just deal with malloc? I mean, I will create shared memory using shmget (key, SHMSZ, IPC_CREAT | 0666), where SHMSZ will have the size of the node structure. Therefore, I only share the head of the list between the two processes. The first entry in the list will have all the values 0, except for the link that will point to the next entry in the list, and this entry is created using malloc, since in my application, since another process will be read only if one process is added / delete entries in the list.
I got one answer that tells me that I cannot use malloc. I do not know why I can not use malloc. Could you tell me why I cannot use malloc?
Below is my code for the above purpose, which I tried, but get a segmentation error.
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;
}
source
share