1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
15 #include <sys/select.h>
16 #include "socketengine_select.h"
19 SelectEngine::SelectEngine(InspIRCd* Instance) : SocketEngine(Instance)
23 memset(writeable, 0, sizeof(writeable));
26 SelectEngine::~SelectEngine()
30 bool SelectEngine::AddFd(EventHandler* eh)
33 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
36 if (GetRemainingFds() <= 1)
46 ServerInstance->Log(DEBUG,"New file descriptor: %d", fd);
50 void SelectEngine::WantWrite(EventHandler* eh)
52 writeable[eh->GetFd()] = true;
55 bool SelectEngine::DelFd(EventHandler* eh, bool force)
59 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
62 std::map<int,int>::iterator t = fds.find(fd);
70 ServerInstance->Log(DEBUG,"Remove file descriptor: %d", fd);
74 int SelectEngine::GetMaxFds()
79 int SelectEngine::GetRemainingFds()
81 return FD_SETSIZE - CurrentSetSize;
84 int SelectEngine::DispatchEvents()
89 EventHandler* ev[MAX_DESCRIPTORS];
97 for (std::map<int,int>::iterator a = fds.begin(); a != fds.end(); a++)
99 if (ref[a->second]->Readable())
100 FD_SET (a->second, &rfdset);
102 FD_SET (a->second, &wfdset);
103 if (writeable[a->second])
104 FD_SET (a->second, &wfdset);
106 FD_SET (a->second, &errfdset);
110 sresult = select(FD_SETSIZE, &rfdset, &wfdset, &errfdset, &tval);
113 for (std::map<int,int>::iterator a = fds.begin(); a != fds.end(); a++)
115 if ((FD_ISSET (a->second, &rfdset)) || (FD_ISSET (a->second, &wfdset)) || FD_ISSET (a->second, &errfdset))
117 ev[result++] = ref[a->second];
122 /** An event handler may remove its own descriptor from the list, therefore it is not
123 * safe to directly iterate over the list and dispatch events there with STL iterators.
124 * Thats a shame because it makes this code slower and more resource intensive, but maybe
125 * the user should stop using select(), as select() smells anyway.
127 for (int i = 0; i < result; i++)
131 if (FD_ISSET (ev[i]->GetFd(), &errfdset))
135 if (getsockopt(ev[i]->GetFd(), SOL_SOCKET, SO_ERROR, &errcode, &codesize) < 0)
138 ev[i]->HandleEvent(EVENT_ERROR, errcode);
144 if (writeable[ev[i]->GetFd()])
146 writeable[ev[i]->GetFd()] = false;
148 ev[i]->HandleEvent(EVENT_WRITE);
153 ev[i]->HandleEvent(ev[i]->Readable() ? EVENT_READ : EVENT_WRITE);
162 std::string SelectEngine::GetName()