C Socket/Client fork(),共享结构体内存

标签 c sockets struct fork shared-memory

我试图在我的 C 服务器上共享结构的内存,得到以下代码

// Before the main
struct Esami {
    char nome[20];
    char cognome[20];
    char matricola[20];
    char voto[20];
};

struct Appelli {
    int stato;
    char dipartimento[20];
    char cdl[20];
    char nomeEsame[20];
    char data[20];
    struct Esami esame[10];
    int numEsamiRegistrati;
} *appello[100];

这就是我在我的 fork 中所做的:

// After creating socket, bind(), listen() and so on..
if ((pid = fork()) == 0) {
    shmid = shmget(2009, sizeof(appello), 0666 | IPC_CREAT);
    *appello = shmat(shmid, 0, 0);
    close (listenfd); // Closes the parent socket
    // Operations on this struct (like the one I explained below)
    exit(0);
}

我尝试使用箭头运算符访问结构体的字段,但是程序可能会出现内存错误,因此如果我填充一个字段并尝试例如

printf("Dipartimento: %s", appello[0]-> dipartimento);

服务器程序崩溃:来自客户端的所有其他输入都不再被读取。我设法让它与单个结构变量(如 *appello)一起工作,但是一旦我开始使用数组(*appello[100]),我就会遇到这个问题。

问题是:如何将这个结构体数组的内存段共享给连接到服务器的每个客户端?

请注意,我正在尝试理解大学练习,我必须使用共享内存和 fork 来解决它。

最佳答案

首先只是对您的示例进行评论:

`printf("Dipartimento: %s", appello[0]-> dipartimento);`    
 this space does not belong in any form ^  

注意:,对于下面的注释,我没有你的结构成员struct Esami esame[10];的定义,因此必须简化所有插图中结构的表示。

下一点,为了说明不同的方法,请更改:

struct Appelli {
    int stato;
    ....
    int numEsamiRegistrati;
} *appello[100];  

收件人:

typedef struct {
    int stato;
    ....
    int numEsamiRegistrati;
} APPELLO;
APPELLO appello[100], *pAppello;

在 main()(或代码的任何可执行部分)中执行此初始化:

pAppello, = &appello[0];//initializes your pointer to a copy of struct  
pAppello = malloc(sizeof(APPELLO));  

然后,当使用指针时,像这样引用成员:

pAppello->cdl;//use -> for pointer 

使用数组时,请像这样引用成员:

appello[0].cdl;//use . for non-pointer   

如果您想要一个指针数组,则以不同的方式初始化:

pAppello = &appello[0];//initializes your pointer to a copy of struct  
pAppello = malloc(sizeof(APPELLO)*100); //provides 100 instances of pAppello

现在,您有了一个指向该结构的指针数组,您将再次 使用 . 访问其成员:

pAppello[0].cdl;

这里有一个很好的补充阅读 tutorial on C structures

关于C Socket/Client fork(),共享结构体内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28397757/

相关文章:

c - 指针类型与 PyArray_SimpleNew 不匹配

在 C 中检查结构数组是否为 'empty'

c - Linux 如何缓冲数据报套接字?

c - g_io_channel + socket = server ,仍然没有收到正确的数据,只得到一个客户端?用C语言

C 全局结构 : "error: expected expression before ' {' token"

c - 使用 printf 打印 UTF-8 字符串 - 宽字符串文字与多字节字符串文字

c - for循环的输出?

c++ - 使用Boost Asio时获取 “resolve: Host not found (authoritative)”异常

arrays - swift - 在结构数组上使用 .map

c - c语言调用函数什么时候加 '&'什么时候不加?