在属于同一父母的多个子过程之间共享记忆
我正在尝试基于主/从架构创建客户端/服务器应用程序。父级服务器负责从客户端处理新的套接字请求,并使用客户端交互发生的fork()。
我想在子进程添加节点的应用程序中创建一个链接列表,并且每个其他孩子都可以访问它。我尝试使用MMAP和SHMGET创建共享存储器,但是在第一个孩子创建列表之后,其他过程无法读取链接列表。
节点结构:
struct node{
char data[1024];
struct node *next;
};
MMAP方法:
void* create_shared_memory(size_t size){
int protection = PROT_READ |PROT_WRITE;
int visibility = MAP_SHARED | MAP_ANONYMOUS;
return mmap(NULL, size, protection, visibility, -1, 0);
}
SHMGET方法:
void * my_malloc(int size)
{
void * ptr = NULL;
key_current = key_first++;
int shm_id;
if ((shm_id = shmget(key_current, size , IPC_CREAT | 0666)) < 0) {
perror("shmget error.");printf("errno= %d EINVAL=%d \n ", errno , EINVAL);
return NULL;
}
if ((ptr = shmat(shm_id, NULL, 0)) == (void *) - 1) {
perror("shmat error");
//exit(1);
return NULL;
}
current_index ++ ;
shm_id_arr[current_index] = shm_id ;
return ptr;
}
I am trying to create Client/Server application based on master/slave architecture. The parent Server is responsible for handling new socket requests from client and uses fork() in which the client interaction happens.
I want to create a Linked List in the application in which the child processes add nodes and it is accessible to every other child. I have tried creating share memory using mmap and shmget but other processes are not able to read the linked list after the first child creates the list.
node structure:
struct node{
char data[1024];
struct node *next;
};
mmap approach:
void* create_shared_memory(size_t size){
int protection = PROT_READ |PROT_WRITE;
int visibility = MAP_SHARED | MAP_ANONYMOUS;
return mmap(NULL, size, protection, visibility, -1, 0);
}
shmget approach:
void * my_malloc(int size)
{
void * ptr = NULL;
key_current = key_first++;
int shm_id;
if ((shm_id = shmget(key_current, size , IPC_CREAT | 0666)) < 0) {
perror("shmget error.");printf("errno= %d EINVAL=%d \n ", errno , EINVAL);
return NULL;
}
if ((ptr = shmat(shm_id, NULL, 0)) == (void *) - 1) {
perror("shmat error");
//exit(1);
return NULL;
}
current_index ++ ;
shm_id_arr[current_index] = shm_id ;
return ptr;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我通过创建一个带有预定义数量
node
元素的数组的数组,使用共享存储器和初始化服务器来聆听客户端请求之前的所有索引,并使用fork()。
I solved this by creating an array with predefined number of
node
elements in the parent process using shared memory and initializing all of the indices before the server listens for client requests and usesfork()
.