Andy
Andy

Reputation: 407

C++ put a struct in shared memory

I want to write a chat room program of C++, and I will use fork() after accept(), all of the clients will communicate by shared memory, the following is part of my code, I put a struct in shared memory, but i get compile error. How can I fix it, or someone can give me an example, thanks!

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);
}

The error message is
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 「...」

Upvotes: 0

Views: 4312

Answers (1)

user1773602
user1773602

Reputation:

Use a pointer, not value

ClientList* shared_memory;
     here ^

shared_memory = (ClientList* ) shmat (segment_id, 0, 0);
                  and here ^

Ah, and then your sizeof will look like this

const int shared_segment_size = sizeof(ClientList);

Upvotes: 1

Related Questions