Back to home page

Enduro/X

 
 

    


0001 #ifdef WIN32
0002 
0003 #include "cgreen/internal/cgreen_pipe.h"
0004 #include <unistd.h>
0005 #include <stdio.h>
0006 #include <winsock2.h>
0007 #include <wincompat.h>
0008 
0009 
0010 #ifdef __cplusplus
0011 namespace cgreen {
0012 #endif
0013 
0014 
0015 ssize_t cgreen_pipe_read(int p, void *buf, size_t count)
0016 {
0017     DWORD bytesRead;
0018 
0019     ReadFile((HANDLE)p, buf, (DWORD)count, &bytesRead, NULL);
0020 
0021     return bytesRead;
0022 }
0023 
0024 ssize_t cgreen_pipe_write(int p, const void *buf, size_t count)
0025 {
0026     DWORD bytesWritten;
0027 
0028     WriteFile((HANDLE)p, buf, (DWORD)count, &bytesWritten, NULL);
0029 
0030     if (bytesWritten != count)
0031     {
0032         printf("failed to write %d bytes - error = %d\n",count,GetLastError());
0033     }
0034 
0035     return bytesWritten;
0036 }
0037 
0038 int cgreen_pipe_open(int pipes[2])
0039 {
0040     SECURITY_ATTRIBUTES saAttr = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
0041     char handleString[256];
0042     DWORD result;
0043 
0044     //figure out if we are a child process, and if so, use the handle provided by our parent
0045     result = GetEnvironmentVariableA(CGREEN_READ_HANDLE,handleString,sizeof(handleString));
0046 
0047     if (result) //we are a child process
0048     {
0049         pipes[0] = (int)atoi(handleString);
0050         result = GetEnvironmentVariableA(CGREEN_WRITE_HANDLE,handleString,sizeof(handleString));
0051         pipes[1] = (int)atoi(handleString);
0052 
0053         //now that we have retrieved these handles, clear the environment variables so
0054         //that subsequent calls to this function will create new pipes
0055         //(This is needed for unit tests "will_report_beginning_and_successful_finishing_of_test"
0056         //and "will_report_failing_of_test_only_once")
0057         SetEnvironmentVariableA(CGREEN_READ_HANDLE,NULL);
0058         SetEnvironmentVariableA(CGREEN_WRITE_HANDLE,NULL);
0059     }
0060     else
0061     {
0062         HANDLE readpipe,writepipe;
0063         DWORD mode = PIPE_READMODE_BYTE | PIPE_NOWAIT;
0064         const DWORD DEFAULT_BUFFER_SIZE = 0;
0065 
0066         if (!CreatePipe(&readpipe, &writepipe, &saAttr, DEFAULT_BUFFER_SIZE))
0067             return -1;
0068 
0069         //turn on NOWAIT
0070         if (!SetNamedPipeHandleState(readpipe,&mode,NULL,NULL))
0071         {
0072             fprintf(stderr, "could not set file status flag on read pipe\n");
0073             return -1;
0074         }
0075 
0076         pipes[0] = (int)readpipe;
0077         pipes[1] = (int)writepipe;
0078     }
0079 
0080     return 0;
0081 }
0082 
0083 void cgreen_pipe_close(int p)
0084 {
0085     CloseHandle((HANDLE)p);
0086 }
0087 
0088 
0089 #ifdef __cplusplus
0090 } // namespace cgreen
0091 #endif
0092 
0093 #endif
0094 /* vim: set ts=4 sw=4 et cindent: */