【发布时间】:2016-08-05 03:01:37
【问题描述】:
我有以下简单的应用程序。这已经被剥夺了错误处理等,好吧,一个最小的完整示例。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
//#define SHM_SIZE 1024 /* make it a 1K shared memory segment */
struct node
{
int x;
struct node *next;
};
int main(int argc, char *argv[])
{
struct node *root[argc+1];
if (argc > 1)
{
int i;
root[0]= (struct node *) malloc( sizeof(struct node) );
for (i=0; i<argc-1; i++)
{
root[i]->x = (int)(*argv[i+1]-'0');
//root[i]->next=&root[i]+sizeof(struct node);
root[i+1]=(struct node *) malloc( sizeof(struct node) ); //Okay, wastes a few ops
root[i]->next=root[i+1];
}
free(root[i]->next);
root[i]=NULL;
}
key_t key;
int shmid;
struct node *data;
key = ftok("test1", 'O');
shmid = shmget(key, (size_t)(sizeof(struct node)*1000), 0777 | IPC_CREAT);
data = shmat(shmid, (void *)0, 0);
printf("%p", &data);
if (argc != 1)
{
int z=0;
for (z=0;z<argc-1;z++){
*(data+sizeof(struct node)*z)=*root[z];
if (z) (data+sizeof (struct node)*(z-1))->next=(data+sizeof (struct node)*z);
}
(data+z)->next=0;
}
if (argc)
{
printf("This is the routine that will retrieve the linked list from shared memory when we are done.");
struct node *pointer;
pointer=data;
printf("%p", data);
while (pointer->next != 0)
{
printf("\n Data: %i",pointer->x);
pointer=pointer->next;
}
}
/* detach from the segment: */
if (shmdt(data) == -1)
{
perror("shmdt");
exit(1);
}
return 0;
}
基本上,每当我尝试从创建它的进程访问共享内存时,我的输出看起来都不错。每次我从未创建共享内存的进程(argc=1)打开共享内存时,程序就会出现段错误。如果有人能告诉我原因,我将不胜感激!
【问题讨论】:
-
想必,
shmget调用在只读取的程序中是不同的,这就是为什么你应该发布一个minimal, complete, and verifiable example。 -
我们只能猜测
root是什么以及它来自哪里等等。 -
啊,够公平的家伙,我只是虽然我做了一些愚蠢到显而易见的事情。固定。
-
free(root[i]->next);释放一个未初始化的指针 -
data+sizeof(struct node)*z是可疑的。也许你的意思是那条线是data[z] = *root[z];。下一行的data+sizeof也可能是错误的
标签: c linked-list shared-memory