我想写一个C ++的聊天室程序,我会在fork()
之后使用accept()
,
所有客户端都将通过共享内存进行通信,以下是我的代码的一部分,
我在共享内存中放了一个struct,但是我得到了编译错误。
我该如何解决,或者有人可以给我一个例子,谢谢!
typedef struct ClientList{
int pid[30];
int whoid[30];
string name[30];
bool online[30];
string ip[30];
int port[30];
string file[30][30];
int pid_who[30][30];
int onlineUser;
}ClientList;
/*Shared memory*/
int segment_id;
ClientList shared_memory;
struct shmid_ds shmbuffer;
int segment_size;
const int shared_segment_size = sizeof(shared_memory);
int main(int argc, char* argv[])
{
/* Allocate a shared memory segment. */
segment_id = shmget (IPC_PRIVATE, shared_segment_size, IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
/* Attach the shared memory segment. */
shared_memory = (ClientList) shmat (segment_id, 0, 0);
printf ("shared memory attached at address %p\n", shared_memory);
/* Determine the segment’s size. */
shmctl (segment_id, IPC_STAT, &shmbuffer);
segment_size = shmbuffer.shm_segsz;
printf ("segment size: %d\n", segment_size);
}
错误消息为
pipe.cpp: In function 「int main(int, char**)」:
pipe.cpp:57:55: 錯誤:對 「ClientList::ClientList(void*)」 的呼叫沒有匹配的函式
pipe.cpp:57:55: 附註:candidates are:
pipe.cpp:31:16: 附註:ClientList::ClientList()
pipe.cpp:31:16: 附註: candidate expects 0 arguments, 1 provided
pipe.cpp:31:16: 附註:ClientList::ClientList(const ClientList&)
pipe.cpp:31:16: 附註: no known conversion for argument 1 from 「void*」 to 「const ClientList&」
pipe.cpp:58:66: 錯誤:cannot pass objects of non-trivially-copyable type 「ClientList {aka struct ClientList}」 through 「...」
答案 0 :(得分:1)
使用指针,而不是值
ClientList* shared_memory;
here ^
shared_memory = (ClientList* ) shmat (segment_id, 0, 0);
and here ^
啊,然后你的sizeof看起来像这样
const int shared_segment_size = sizeof(ClientList);