我有以下 C++ 代码:
map<string, map<string, deque<Event> > > events;
int main(){
//set up socket and stuff here (omitted for clarity)
while(1){
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &client_len);
if (newsockfd < 0)
error("ERROR on accept");
pid = fork();
if (pid < 0)
error("ERROR on event server fork");
if (pid == 0){ //Child Process
close(sockfd);
//do stuff here
read_and_send_ack (newsockfd);
exit(0);
}
else //Parent Process
close(newsockfd);
}
void read_and_send_ack (int sockfd)
{
// buffer is basically a string
//do some non important stuff here, omitted for clarity
event_received(buffer, &events);
}
void event_received(char* event_info, map<string, map<string, deque<Event> > >* events)
{
Event event = Event(event_info);
(*events)[string(event.device)][string(event.dev_id)].push_back(event);
//print keys to test if events are being modified each turn
for (map<string, map<string, deque<Event> > >::iterator it = events->begin(); it!=events->end(); ++it)
cout << it->first;
}
我希望每次 while 循环收到要添加到容器的内容时,都会修改全局容器“事件”。但这种变化并没有持续下去。结果,每当我打印出密钥时,容器中只有一个密钥。到底是怎么回事?我认为所有进程/线程都可以访问 C++ 中的同一个全局变量。