Skip to content

Commit

Permalink
Add low-level fd handling
Browse files Browse the repository at this point in the history
This adds handling of low-level file descriptor polling for read, write and
timeout.

Signed-off-by: Julien Danjou <julien@danjou.info>
  • Loading branch information
jd committed Jan 14, 2013
1 parent 16576a3 commit 0252bf9
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
1 change: 1 addition & 0 deletions cl-async.asd
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
:components
((:file "package")
(:file "base" :depends-on ("package"))
(:file "fd" :depends-on ("base"))
(:file "timer" :depends-on ("base"))
(:file "dns" :depends-on ("base"))
(:file "tcp" :depends-on ("dns"))
Expand Down
46 changes: 46 additions & 0 deletions fd.lisp
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
(in-package :cl-async)

(cffi:defcallback fd-cb :void ((fd :int) (what :short) (data-pointer :pointer))
(declare (ignore fd))
(let* ((ev (deref-data-from-pointer data-pointer))
(callbacks (get-callbacks data-pointer))
(timeout-cb (getf callbacks :timeout-cb))
(read-cb (getf callbacks :read-cb))
(write-cb (getf callbacks :write-cb))
(event-cb (getf callbacks :event-cb)))
(catch-app-errors event-cb
(when (and (< 0 (logand what le:+ev-read+))
read-cb)
(funcall read-cb))
(when (and (< 0 (logand what le:+ev-write+))
write-cb)
(funcall write-cb))
(when (and (< 0 (logand what le:+ev-timeout+))
timeout-cb)
(funcall timeout-cb)))))

(defun fd-add (fd &key event-cb read-cb write-cb timeout-cb timeout)
"Run a function, asynchronously, when the specified file descriptor is
ready for write or read operations. An event loop must be running for
this to work."
(check-event-loop-running)
(let* ((data-pointer (create-data-pointer))
(ev (le:event-new *event-base*
fd
;; listen to read/timeout events, and keep listening
(logior
(if timeout-cb le:+ev-timeout+ 0)
(if read-cb le:+ev-read+ 0)
(if write-cb le:+ev-write+ 0)
le:+ev-persist+)
(cffi:callback fd-cb)
data-pointer)))
(save-callbacks data-pointer (list :read-cb read-cb
:write-cb write-cb
:timeout-cb timeout-cb
:event-cb event-cb))
(attach-data-to-pointer data-pointer ev)
(if (numberp timeout)
(with-struct-timeval time-c timeout
(le:event-add ev time-c))
(le:event-add ev (cffi:null-pointer)))))
3 changes: 3 additions & 0 deletions package.lisp
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@
;; timer functions
#:delay

;; fd functions
#:fd-add

;; signal numbers
#:+sighup+
#:+sigint+
Expand Down

0 comments on commit 0252bf9

Please sign in to comment.