This program acts like an ideal babysitter. It listens for all we want to tell it, until we make a long (10 seconds) pause. Once we do, it assumes the baby is sleeping and exits.
The program uses two sources of events - the standard input stream and the timer. Each time the descriptor #0 shows there's some data there, the program tries to read 4k chars from stdin (for most cases, it is sufficient to read all the data which currently there) and resets the time-based event to be 10 seconds from now.
Once the time event occurs, it assumes there was no activity for 10 seconds, so we can assume the baby went to sleep.
/* This program listens to you no matter what bullshit you tell, until you get tired and sleepy. If you keep silence for 10 seconds, the program assumes you went to sleep and it is no longer needed, so it terminates. */ #include <stdio.h> #include <unistd.h> #include "sue_sel.hpp" class PerfectListener : private SUEFdHandler, private SUETimeoutHandler { SUEEventSelector *selector; virtual bool WantRead() { return true; } virtual bool WantWrite() { return false; } virtual void TimeoutHandle() { selector->Break(); printf("Sleep, baby, sleep...\n"); } virtual void FdHandle(bool, bool, bool) { char buf[4096]; if(read(0, buf, sizeof(buf))<=0) { printf("Error reading stdin or end of file\n"); selector->Break(); return; } selector->RemoveTimeoutHandler(this); SetFromNow(10); selector->RegisterTimeoutHandler(this); } public: PerfectListener(SUEEventSelector *sel) { selector = sel; SetFd(0); // stdin SetFromNow(10); selector->RegisterFdHandler(this); selector->RegisterTimeoutHandler(this); } ~PerfectListener() {} }; int main() { SUEEventSelector selector; PerfectListener pfl(&selector); printf("Entering the main loop... \n"); selector.Go(); printf("Main loop exited\n"); return 0; }