C ++:未修改全局容器

时间:2013-06-10 07:18:59

标签: c++ containers global

我有以下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 ++中访问相同的全局变量。

1 个答案:

答案 0 :(得分:1)

将我的评论转化为答案。

当子进程由fork()创建时,它会获得自己的进程状态副本,包括全局变量。

如果您希望父进程和子进程进行通信,则必须为它们设置某种形式的通道(例如管道,文件,共享内存或类似内容)。