我试图在我的 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/