Reputation: 117
I have the following C++ code:
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;
}
I expect the global container "events" to be modified each time the while loop receives something to add to the container. But the change does not persist. As a result, whenever I print out the keys, only one key is in the container. What is going on? I thought all processes/threads can access the same global variable in C++.
Upvotes: 0
Views: 168
Reputation: 171167
Turning my comment into an answer.
When the child process is created by fork()
, it gets its own copy of the process state, including global variables.
If you want the parent and child process to communicate, you'll have to set up some form of channel for them to do so (such as a pipe, a file, shared memory or something similar).
Upvotes: 1