1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
18 #include <sys/select.h>
19 #include "socketengine_select.h"
22 SelectEngine::SelectEngine(InspIRCd* Instance) : SocketEngine(Instance)
24 ServerInstance->Log(DEBUG,"SelectEngine::SelectEngine()");
29 SelectEngine::~SelectEngine()
31 ServerInstance->Log(DEBUG,"SelectEngine::~SelectEngine()");
34 bool SelectEngine::AddFd(EventHandler* eh)
37 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
39 ServerInstance->Log(DEFAULT,"ERROR: FD of %d added above max of %d",fd,MAX_DESCRIPTORS);
42 if (GetRemainingFds() <= 1)
44 ServerInstance->Log(DEFAULT,"ERROR: System out of file descriptors!");
54 ServerInstance->Log(DEBUG,"Add socket %d",fd);
60 bool SelectEngine::DelFd(EventHandler* eh)
64 ServerInstance->Log(DEBUG,"SelectEngine::DelFd(%d)",fd);
66 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
69 std::map<int,int>::iterator t = fds.find(fd);
73 ServerInstance->Log(DEBUG,"Deleted fd %d",fd);
81 int SelectEngine::GetMaxFds()
86 int SelectEngine::GetRemainingFds()
88 return FD_SETSIZE - CurrentSetSize;
91 int SelectEngine::DispatchEvents()
96 EventHandler* ev[MAX_DESCRIPTOR];
101 for (std::map<int,int>::iterator a = fds.begin(); a != fds.end(); a++)
103 if (ref[a->second]->Readable())
105 FD_SET (a->second, &rfdset);
109 FD_SET (a->second, &wfdset);
115 sresult = select(FD_SETSIZE, &rfdset, &wfdset, NULL, &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)))
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++)
134 ServerInstance->Log(DEBUG,"Handle %s event on fd %d",ev[i]->Readable() ? "read" : "write", ev[i]->GetFd());
135 ev[i]->HandleEvent(ev[i]->Readable() ? EVENT_READ : EVENT_WRITE);
141 std::string SelectEngine::GetName()