我想分享我的C服务器上的一个结构的记忆,得到了下面的代码交流电插座/客户端fork()的,共享内存结构
// 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];
这是我在我的叉子做:
// 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]),我就会遇到这个问题。
问题是:如何将此数组结构的内存段共享给连接到服务器的每个客户端?
请注意,我试图了解大学的练习,我必须用共享内存和分叉解决它。
为什么你不在串口上(serialize)(http://en.wikipedia.org/wiki/Serialization)你的数据结构?另请参阅[这个答案](http://stackoverflow.com/a/28373401/841108)到一个相关的问题... – 2015-02-08 19:46:07