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)
21 ServerInstance->Log(DEBUG,"SelectEngine::SelectEngine()");
24 memset(writeable, 0, sizeof(writeable));
27 SelectEngine::~SelectEngine()
29 ServerInstance->Log(DEBUG,"SelectEngine::~SelectEngine()");
32 bool SelectEngine::AddFd(EventHandler* eh)
35 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
37 ServerInstance->Log(DEBUG,"ERROR: FD of %d added above max of %d",fd,MAX_DESCRIPTORS);
40 if (GetRemainingFds() <= 1)
42 ServerInstance->Log(DEBUG,"ERROR: System out of file descriptors!");
52 ServerInstance->Log(DEBUG,"Add socket %d",fd);
58 void SelectEngine::WantWrite(EventHandler* eh)
60 writeable[eh->GetFd()] = true;
63 bool SelectEngine::DelFd(EventHandler* eh)
67 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
70 std::map<int,int>::iterator t = fds.find(fd);
79 int SelectEngine::GetMaxFds()
84 int SelectEngine::GetRemainingFds()
86 return FD_SETSIZE - CurrentSetSize;
89 int SelectEngine::DispatchEvents()
94 EventHandler* ev[MAX_DESCRIPTORS];
102 for (std::map<int,int>::iterator a = fds.begin(); a != fds.end(); a++)
104 if (ref[a->second]->Readable())
105 FD_SET (a->second, &rfdset);
107 FD_SET (a->second, &wfdset);
108 if (writeable[a->second])
109 FD_SET (a->second, &wfdset);
111 FD_SET (a->second, &errfdset);
115 sresult = select(FD_SETSIZE, &rfdset, &wfdset, &errfdset, &tval);
118 for (std::map<int,int>::iterator a = fds.begin(); a != fds.end(); a++)
120 if ((FD_ISSET (a->second, &rfdset)) || (FD_ISSET (a->second, &wfdset)) || FD_ISSET (a->second, &errfdset))
122 ev[result++] = ref[a->second];
127 /** An event handler may remove its own descriptor from the list, therefore it is not
128 * safe to directly iterate over the list and dispatch events there with STL iterators.
129 * Thats a shame because it makes this code slower and more resource intensive, but maybe
130 * the user should stop using select(), as select() smells anyway.
132 for (int i = 0; i < result; i++)
136 if (FD_ISSET (ev[i]->GetFd(), &errfdset))
140 if (getsockopt(ev[i]->GetFd(), SOL_SOCKET, SO_ERROR, &errcode, &codesize) < 0)
143 ev[i]->HandleEvent(EVENT_ERROR, errcode);
149 if (writeable[ev[i]->GetFd()])
152 ev[i]->HandleEvent(EVENT_WRITE);
153 writeable[ev[i]->GetFd()] = false;
159 ev[i]->HandleEvent(ev[i]->Readable() ? EVENT_READ : EVENT_WRITE);
168 std::string SelectEngine::GetName()