{
    "content": [
        {
            "type": "text",
            "text": "# epoll(7) (man)\n\n**Summary:** epoll - I/O event notification facility\n\n## See Also\n\n- epollcreate(2)\n- epollcreate1(2)\n- epollctl(2)\n- epollwait(2)\n- poll(2)\n- select(2)\n\n## Section Outline\n\n- **NAME** (2 lines)\n- **SYNOPSIS** (1 lines) — 1 subsections\n  - #include <sys/epoll.h> (1 lines)\n- **DESCRIPTION** (28 lines) — 8 subsections\n  - Level-triggered and edge-triggered (50 lines)\n  - Interaction with autosleep (11 lines)\n  - /proc interfaces (9 lines)\n  - Example for suggested usage (62 lines)\n  - Questions and answers (84 lines)\n  - Possible pitfalls and ways to avoid them (1 lines)\n  - o Starvation (edge-triggered) (8 lines)\n  - o If using an event cache... (13 lines)\n- **VERSIONS** (3 lines)\n- **CONFORMING TO** (3 lines)\n- **NOTES** (7 lines)\n- **SEE ALSO** (2 lines)\n- **COLOPHON** (7 lines)\n\n## Full Content\n\n### NAME\n\nepoll - I/O event notification facility\n\n### SYNOPSIS\n\n#### #include <sys/epoll.h>\n\n### DESCRIPTION\n\nThe epoll API performs a similar task to poll(2): monitoring multiple file descriptors to see\nif I/O is possible on any of them.  The epoll API can be used either as an edge-triggered  or\na level-triggered interface and scales well to large numbers of watched file descriptors.\n\nThe  central  concept  of  the  epoll  API is the epoll instance, an in-kernel data structure\nwhich, from a user-space perspective, can be considered as a container for two lists:\n\n• The interest list (sometimes also called the epoll set): the set of file  descriptors  that\nthe process has registered an interest in monitoring.\n\n• The  ready list: the set of file descriptors that are \"ready\" for I/O.  The ready list is a\nsubset of (or, more precisely, a set of references to) the file descriptors in the interest\nlist.  The ready list is dynamically populated by the kernel as a result of I/O activity on\nthose file descriptors.\n\nThe following system calls are provided to create and manage an epoll instance:\n\n• epollcreate(2) creates a new epoll instance and returns a  file  descriptor  referring  to\nthat  instance.   (The more recent epollcreate1(2) extends the functionality of epollcre‐‐\nate(2).)\n\n• Interest in particular file descriptors is then registered  via  epollctl(2),  which  adds\nitems to the interest list of the epoll instance.\n\n• epollwait(2)  waits for I/O events, blocking the calling thread if no events are currently\navailable.  (This system call can be thought of as fetching items from the  ready  list  of\nthe epoll instance.)\n\n#### Level-triggered and edge-triggered\n\nThe  epoll  event distribution interface is able to behave both as edge-triggered (ET) and as\nlevel-triggered (LT).  The difference between the two mechanisms can be described as follows.\nSuppose that this scenario happens:\n\n1. The  file  descriptor  that  represents the read side of a pipe (rfd) is registered on the\nepoll instance.\n\n2. A pipe writer writes 2 kB of data on the write side of the pipe.\n\n3. A call to epollwait(2) is done that will return rfd as a ready file descriptor.\n\n4. The pipe reader reads 1 kB of data from rfd.\n\n5. A call to epollwait(2) is done.\n\nIf the rfd file descriptor has been added to the epoll interface  using  the  EPOLLET  (edge-\ntriggered)  flag,  the  call  to  epollwait(2) done in step 5 will probably hang despite the\navailable data still present in the file input buffer; meanwhile the remote peer might be ex‐\npecting a response based on the data it already sent.  The reason for this is that edge-trig‐\ngered mode delivers events only when changes occur on the monitored file descriptor.  So,  in\nstep 5 the caller might end up waiting for some data that is already present inside the input\nbuffer.  In the above example, an event on rfd will be generated because of the write done in\n2  and  the  event is consumed in 3.  Since the read operation done in 4 does not consume the\nwhole buffer data, the call to epollwait(2) done in step 5 might block indefinitely.\n\nAn application that employs the EPOLLET flag should use nonblocking file descriptors to avoid\nhaving  a  blocking  read  or write starve a task that is handling multiple file descriptors.\nThe suggested way to use epoll as an edge-triggered (EPOLLET) interface is as follows:\n\na) with nonblocking file descriptors; and\n\nb) by waiting for an event only after read(2) or write(2) return EAGAIN.\n\nBy contrast, when used as a level-triggered interface (the default, when EPOLLET is not spec‐\nified),  epoll  is simply a faster poll(2), and can be used wherever the latter is used since\nit shares the same semantics.\n\nSince even with edge-triggered epoll, multiple events can be generated upon receipt of multi‐\nple chunks of data, the caller has the option to specify the EPOLLONESHOT flag, to tell epoll\nto disable the associated file descriptor after the receipt of an event  with  epollwait(2).\nWhen  the EPOLLONESHOT flag is specified, it is the caller's responsibility to rearm the file\ndescriptor using epollctl(2) with EPOLLCTLMOD.\n\nIf multiple threads (or processes, if child processes have inherited the epoll file  descrip‐\ntor  across  fork(2))  are blocked in epollwait(2) waiting on the same epoll file descriptor\nand a file descriptor in the interest list that is marked for edge-triggered (EPOLLET)  noti‐\nfication  becomes ready, just one of the threads (or processes) is awoken from epollwait(2).\nThis provides a useful optimization for avoiding \"thundering herd\" wake-ups in  some  scenar‐\nios.\n\n#### Interaction with autosleep\n\nIf  the system is in autosleep mode via /sys/power/autosleep and an event happens which wakes\nthe device from sleep, the device driver will keep the device awake only until that event  is\nqueued.   To keep the device awake until the event has been processed, it is necessary to use\nthe epollctl(2) EPOLLWAKEUP flag.\n\nWhen the EPOLLWAKEUP flag is set in the events field for a  struct  epollevent,  the  system\nwill  be kept awake from the moment the event is queued, through the epollwait(2) call which\nreturns the event until the subsequent epollwait(2) call.  If the event should keep the sys‐\ntem  awake  beyond  that  time,  then  a separate wakelock should be taken before the second\nepollwait(2) call.\n\n#### /proc interfaces\n\nThe following interfaces can be used to limit the amount of kernel memory consumed by epoll:\n\n/proc/sys/fs/epoll/maxuserwatches (since Linux 2.6.28)\nThis specifies a limit on the total number of file descriptors that a user can  regis‐\nter  across  all  epoll instances on the system.  The limit is per real user ID.  Each\nregistered file descriptor costs roughly 90 bytes on a 32-bit kernel, and roughly  160\nbytes  on  a 64-bit kernel.  Currently, the default value for maxuserwatches is 1/25\n(4%) of the available low memory, divided by the registration cost in bytes.\n\n#### Example for suggested usage\n\nWhile the usage of epoll when employed as a level-triggered interface does have the same  se‐\nmantics  as  poll(2), the edge-triggered usage requires more clarification to avoid stalls in\nthe application event loop.  In this example, listener is a nonblocking socket on which  lis‐‐\nten(2)  has  been  called.  The function dousefd() uses the new ready file descriptor until\nEAGAIN is returned by either read(2) or write(2).  An event-driven state machine  application\nshould,  after  having  received EAGAIN, record its current state so that at the next call to\ndousefd() it will continue to read(2) or write(2) from where it stopped before.\n\n#define MAXEVENTS 10\nstruct epollevent ev, events[MAXEVENTS];\nint listensock, connsock, nfds, epollfd;\n\n/* Code to set up listening socket, 'listensock',\n(socket(), bind(), listen()) omitted */\n\nepollfd = epollcreate1(0);\nif (epollfd == -1) {\nperror(\"epollcreate1\");\nexit(EXITFAILURE);\n}\n\nev.events = EPOLLIN;\nev.data.fd = listensock;\nif (epollctl(epollfd, EPOLLCTLADD, listensock, &ev) == -1) {\nperror(\"epollctl: listensock\");\nexit(EXITFAILURE);\n}\n\nfor (;;) {\nnfds = epollwait(epollfd, events, MAXEVENTS, -1);\nif (nfds == -1) {\nperror(\"epollwait\");\nexit(EXITFAILURE);\n}\n\nfor (n = 0; n < nfds; ++n) {\nif (events[n].data.fd == listensock) {\nconnsock = accept(listensock,\n(struct sockaddr *) &addr, &addrlen);\nif (connsock == -1) {\nperror(\"accept\");\nexit(EXITFAILURE);\n}\nsetnonblocking(connsock);\nev.events = EPOLLIN | EPOLLET;\nev.data.fd = connsock;\nif (epollctl(epollfd, EPOLLCTLADD, connsock,\n&ev) == -1) {\nperror(\"epollctl: connsock\");\nexit(EXITFAILURE);\n}\n} else {\ndousefd(events[n].data.fd);\n}\n}\n}\n\nWhen used as an edge-triggered interface, for performance reasons, it is possible to add  the\nfile descriptor inside the epoll interface (EPOLLCTLADD) once by specifying (EPOLLIN|EPOLL‐‐\nOUT).  This allows you to avoid continuously switching between EPOLLIN and  EPOLLOUT  calling\nepollctl(2) with EPOLLCTLMOD.\n\n#### Questions and answers\n\n0.  What is the key used to distinguish the file descriptors registered in an interest list?\n\nThe  key  is  the combination of the file descriptor number and the open file description\n(also known as an \"open file handle\", the kernel's internal  representation  of  an  open\nfile).\n\n1.  What happens if you register the same file descriptor on an epoll instance twice?\n\nYou  will  probably  get  EEXIST.   However,  it  is possible to add a duplicate (dup(2),\ndup2(2), fcntl(2) FDUPFD) file descriptor to the same epoll instance.   This  can  be  a\nuseful  technique  for filtering events, if the duplicate file descriptors are registered\nwith different events masks.\n\n2.  Can two epoll instances wait for the same file descriptor?  If so, are events reported to\nboth epoll file descriptors?\n\nYes, and events would be reported to both.  However, careful programming may be needed to\ndo this correctly.\n\n3.  Is the epoll file descriptor itself poll/epoll/selectable?\n\nYes.  If an epoll file descriptor has events waiting, then  it  will  indicate  as  being\nreadable.\n\n4.  What happens if one attempts to put an epoll file descriptor into its own file descriptor\nset?\n\nThe epollctl(2) call fails (EINVAL).  However, you can add an epoll file descriptor  in‐\nside another epoll file descriptor set.\n\n5.  Can I send an epoll file descriptor over a UNIX domain socket to another process?\n\nYes,  but  it  does not make sense to do this, since the receiving process would not have\ncopies of the file descriptors in the interest list.\n\n6.  Will closing a file descriptor cause it to be removed from all epoll interest lists?\n\nYes, but be aware of the following point.  A file descriptor is a reference  to  an  open\nfile  description  (see  open(2)).   Whenever a file descriptor is duplicated via dup(2),\ndup2(2), fcntl(2) FDUPFD, or fork(2), a new file descriptor referring to the  same  open\nfile  description is created.  An open file description continues to exist until all file\ndescriptors referring to it have been closed.\n\nA file descriptor is removed from an interest list only after all  the  file  descriptors\nreferring to the underlying open file description have been closed.  This means that even\nafter a file descriptor that is part of an interest list has been closed, events  may  be\nreported  for that file descriptor if other file descriptors referring to the same under‐\nlying file description remain open.  To prevent this happening, the file descriptor  must\nbe explicitly removed from the interest list (using epollctl(2) EPOLLCTLDEL) before it\nis duplicated.  Alternatively, the application must ensure that all file descriptors  are\nclosed  (which  may be difficult if file descriptors were duplicated behind the scenes by\nlibrary functions that used dup(2) or fork(2)).\n\n7.  If more than one event occurs between epollwait(2) calls, are they combined or  reported\nseparately?\n\nThey will be combined.\n\n8.  Does  an operation on a file descriptor affect the already collected but not yet reported\nevents?\n\nYou can do two operations on an existing file descriptor.  Remove  would  be  meaningless\nfor this case.  Modify will reread available I/O.\n\n9.  Do  I need to continuously read/write a file descriptor until EAGAIN when using the EPOL‐‐\nLET flag (edge-triggered behavior)?\n\nReceiving an event from epollwait(2) should suggest to you that such file descriptor  is\nready  for  the requested I/O operation.  You must consider it ready until the next (non‐\nblocking) read/write yields EAGAIN.  When and how you will use the file descriptor is en‐\ntirely up to you.\n\nFor  packet/token-oriented files (e.g., datagram socket, terminal in canonical mode), the\nonly way to detect the end of the read/write I/O space is to continue to read/write until\nEAGAIN.\n\nFor  stream-oriented  files  (e.g.,  pipe,  FIFO,  stream socket), the condition that the\nread/write I/O space is exhausted can also be detected by checking  the  amount  of  data\nread  from  / written to the target file descriptor.  For example, if you call read(2) by\nasking to read a certain amount of data and read(2) returns a lower number of bytes,  you\ncan  be sure of having exhausted the read I/O space for the file descriptor.  The same is\ntrue when writing using write(2).  (Avoid this latter technique if you  cannot  guarantee\nthat the monitored file descriptor always refers to a stream-oriented file.)\n\n#### Possible pitfalls and ways to avoid them\n\n#### o Starvation (edge-triggered)\n\nIf  there is a large amount of I/O space, it is possible that by trying to drain it the other\nfiles will not get processed causing starvation.  (This problem is not specific to epoll.)\n\nThe solution is to maintain a ready list and mark the file descriptor as ready in its associ‐\nated data structure, thereby allowing the application to remember which files need to be pro‐\ncessed but still round robin amongst all the ready files.  This also supports ignoring subse‐\nquent events you receive for file descriptors that are already ready.\n\n#### o If using an event cache...\n\nIf you use an event cache or store all the file descriptors returned from epollwait(2), then\nmake sure to provide a way to mark its  closure  dynamically  (i.e.,  caused  by  a  previous\nevent's  processing).   Suppose you receive 100 events from epollwait(2), and in event #47 a\ncondition causes event #13 to be closed.  If you remove the structure and close(2)  the  file\ndescriptor  for event #13, then your event cache might still say there are events waiting for\nthat file descriptor causing confusion.\n\nOne solution for this is to call, during the processing of event 47, epollctl(EPOLLCTLDEL)\nto delete file descriptor 13 and close(2), then mark its associated data structure as removed\nand link it to a cleanup list.  If you find another event for  file  descriptor  13  in  your\nbatch processing, you will discover the file descriptor had been previously removed and there\nwill be no confusion.\n\n### VERSIONS\n\nThe epoll API was introduced in Linux kernel 2.5.44.  Support was added to glibc  in  version\n2.3.2.\n\n### CONFORMING TO\n\nThe epoll API is Linux-specific.  Some other systems provide similar mechanisms, for example,\nFreeBSD has kqueue, and Solaris has /dev/poll.\n\n### NOTES\n\nThe set of file descriptors that is being monitored via  an  epoll  file  descriptor  can  be\nviewed via the entry for the epoll file descriptor in the process's /proc/[pid]/fdinfo direc‐\ntory.  See proc(5) for further details.\n\nThe kcmp(2) KCMPEPOLLTFD operation can be used to test whether a file descriptor is present\nin an epoll instance.\n\n### SEE ALSO\n\nepollcreate(2), epollcreate1(2), epollctl(2), epollwait(2), poll(2), select(2)\n\n### COLOPHON\n\nThis  page  is  part  of  release  5.10 of the Linux man-pages project.  A description of the\nproject, information about reporting bugs, and the latest version of this page, can be  found\nat https://www.kernel.org/doc/man-pages/.\n\n\n\nLinux                                        2019-03-06                                     EPOLL(7)\n\n"
        }
    ],
    "structuredContent": {
        "command": "epoll",
        "section": "7",
        "mode": "man",
        "summary": "epoll - I/O event notification facility",
        "synopsis": "",
        "flags": [],
        "examples": [],
        "see_also": [
            {
                "name": "epollcreate",
                "section": "2",
                "url": "https://www.chedong.com/phpMan.php/man/epollcreate/2/json"
            },
            {
                "name": "epollcreate1",
                "section": "2",
                "url": "https://www.chedong.com/phpMan.php/man/epollcreate1/2/json"
            },
            {
                "name": "epollctl",
                "section": "2",
                "url": "https://www.chedong.com/phpMan.php/man/epollctl/2/json"
            },
            {
                "name": "epollwait",
                "section": "2",
                "url": "https://www.chedong.com/phpMan.php/man/epollwait/2/json"
            },
            {
                "name": "poll",
                "section": "2",
                "url": "https://www.chedong.com/phpMan.php/man/poll/2/json"
            },
            {
                "name": "select",
                "section": "2",
                "url": "https://www.chedong.com/phpMan.php/man/select/2/json"
            }
        ],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "SYNOPSIS",
                "lines": 1,
                "subsections": [
                    {
                        "name": "#include <sys/epoll.h>",
                        "lines": 1
                    }
                ]
            },
            {
                "name": "DESCRIPTION",
                "lines": 28,
                "subsections": [
                    {
                        "name": "Level-triggered and edge-triggered",
                        "lines": 50
                    },
                    {
                        "name": "Interaction with autosleep",
                        "lines": 11
                    },
                    {
                        "name": "/proc interfaces",
                        "lines": 9
                    },
                    {
                        "name": "Example for suggested usage",
                        "lines": 62
                    },
                    {
                        "name": "Questions and answers",
                        "lines": 84
                    },
                    {
                        "name": "Possible pitfalls and ways to avoid them",
                        "lines": 1
                    },
                    {
                        "name": "o Starvation (edge-triggered)",
                        "lines": 8
                    },
                    {
                        "name": "o If using an event cache...",
                        "lines": 13
                    }
                ]
            },
            {
                "name": "VERSIONS",
                "lines": 3,
                "subsections": []
            },
            {
                "name": "CONFORMING TO",
                "lines": 3,
                "subsections": []
            },
            {
                "name": "NOTES",
                "lines": 7,
                "subsections": []
            },
            {
                "name": "SEE ALSO",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "COLOPHON",
                "lines": 7,
                "subsections": []
            }
        ]
    }
}