Commit 81679db3f21e329545c1f243d81a0ada3ca324ec

Thomas de Grivel 2017-04-10T17:39:03

Use close from cffi-posix, add with-socket and with-accept.

diff --git a/cffi-sockets.asd b/cffi-sockets.asd
index 3b657af..f7235c9 100644
--- a/cffi-sockets.asd
+++ b/cffi-sockets.asd
@@ -8,7 +8,7 @@
 
 (defsystem "cffi-sockets"
   :defsystem-depends-on ("cffi-grovel")
-  :depends-on ("cffi" "cffi-errno")
+  :depends-on ("cffi" "cffi-errno" "cffi-posix")
   :components
   ((:file "package")
    (:cffi-grovel-file "grovel-sockets" :depends-on ("package"))
diff --git a/cffi-sockets.lisp b/cffi-sockets.lisp
index 6b17c81..fac4d74 100644
--- a/cffi-sockets.lisp
+++ b/cffi-sockets.lisp
@@ -17,14 +17,10 @@
       (error-errno "socket"))
     s))
 
-(defcfun ("close" c-close) :int
-  (fd :int))
-
-(defun close-sock (fd)
-  (let ((r (c-close fd)))
-    (when (< r 0)
-      (error-errno "close"))
-    r))
+(defmacro with-socket ((var domain type protocol) &body body)
+  `(let ((,var (socket ,domain ,type ,protocol)))
+     (unwind-protect (progn ,@body)
+       (cffi-posix:close ,var))))
 
 (defcstruct sockaddr
   (sa-family sa-family-t)
@@ -112,6 +108,11 @@
 	  (error-errno "accept"))
 	(values s addr)))))
 
+(defmacro with-accept ((var listening-fd) &body body)
+  `(let ((,var (accept ,listening-fd)))
+     (unwind-protect (progn ,@body)
+       (cffi-posix:close ,var))))
+
 (defcfun ("recv" c-recv) ssize-t
   (sockfd :int)
   (buf :pointer)
diff --git a/package.lisp b/package.lisp
index b30d40c..9b0a313 100644
--- a/package.lisp
+++ b/package.lisp
@@ -20,10 +20,11 @@
    #:+sock-cloexec+
    #:file-descriptor
    #:socket
-   #:close-sock
+   #:with-socket
    #:bind-inet
    #:listen-sock
    #:accept
+   #:with-accept
    #:recv
    #:recv-sequence
    #:send