Using new handle cleanup structure
authorArmin Novak <armin.novak@thincast.com>
Wed, 11 Mar 2015 16:57:01 +0000 (17:57 +0100)
committerArmin Novak <armin.novak@thincast.com>
Wed, 11 Mar 2015 16:57:01 +0000 (17:57 +0100)
winpr/libwinpr/synch/semaphore.c

index a6a01fa..7796227 100644 (file)
 
 #ifndef _WIN32
 
+#include <errno.h>
 #include "../handle/handle.h"
 #include "../log.h"
 #define TAG WINPR_TAG("synch.semaphore")
-static pthread_once_t semaphore_initialized = PTHREAD_ONCE_INIT;
-
-static HANDLE_CLOSE_CB _SemaphoreHandleCloseCb;
 
 static BOOL SemaphoreCloseHandle(HANDLE handle);
 
@@ -53,11 +51,33 @@ static BOOL SemaphoreIsHandled(HANDLE handle)
        return TRUE;
 }
 
-static void SemaphoreInitialize(void)
+static int SemaphoreGetFd(HANDLE handle)
+{
+       WINPR_SEMAPHORE *sem = (WINPR_SEMAPHORE *)handle;
+
+       if (!SemaphoreIsHandled(handle))
+               return -1;
+
+       return sem->pipe_fd[0];
+}
+
+static DWORD SemaphoreCleanupHandle(HANDLE handle)
 {
-       _SemaphoreHandleCloseCb.IsHandled = SemaphoreIsHandled;
-       _SemaphoreHandleCloseCb.CloseHandle = SemaphoreCloseHandle;
-       RegisterHandleCloseCb(&_SemaphoreHandleCloseCb);
+       int length;
+       WINPR_SEMAPHORE *sem = (WINPR_SEMAPHORE *)handle;
+
+       if (!SemaphoreIsHandled(handle))
+               return WAIT_FAILED;
+
+       length = read(sem->pipe_fd[0], &length, 1);
+
+       if (length != 1)
+       {
+               WLog_ERR(TAG, "semaphore read() failure [%d] %s", errno, strerror(errno));
+               return WAIT_FAILED;
+       }
+
+       return WAIT_OBJECT_0;
 }
 
 BOOL SemaphoreCloseHandle(HANDLE handle) {
@@ -96,9 +116,6 @@ HANDLE CreateSemaphoreW(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, LONG lIniti
        HANDLE handle;
        WINPR_SEMAPHORE* semaphore;
 
-       if (pthread_once(&semaphore_initialized, SemaphoreInitialize))
-               return NULL;
-
        semaphore = (WINPR_SEMAPHORE*) malloc(sizeof(WINPR_SEMAPHORE));
 
        if (!semaphore)
@@ -107,6 +124,10 @@ HANDLE CreateSemaphoreW(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, LONG lIniti
        semaphore->pipe_fd[0] = -1;
        semaphore->pipe_fd[0] = -1;
        semaphore->sem = (winpr_sem_t*) NULL;
+       semaphore->cb.IsHandled = SemaphoreIsHandled;
+       semaphore->cb.CloseHandle = SemaphoreCloseHandle;
+       semaphore->cb.GetFd = SemaphoreGetFd;
+       semaphore->cb.CleanupHandle = SemaphoreCleanupHandle;
 
        if (semaphore)
        {