00001 #include <string.h>
00002 #include "OSDependent/NamedPipe.h"
00003
00004 #define NPIPE_PREFIX "\\\\.\\pipe\\"
00005 #define NPIPE_MAXSZ 256
00006
00007 NamedPipe::NamedPipe() :
00008 _pipe(NULL)
00009 {
00010 }
00011
00012 NamedPipe::~NamedPipe()
00013 {
00014 close();
00015 }
00016
00017 void
00018 NamedPipe::close()
00019 {
00020 if (_pipe == NULL)
00021 return;
00022 if (_is_server)
00023 DisconnectNamedPipe(_pipe);
00024 CloseHandle(_pipe);
00025 _pipe = NULL;
00026 }
00027
00028 long
00029 NamedPipe::write(char*buffer, long size)
00030 {
00031 if (_pipe == NULL)
00032 return -1;
00033
00034 DWORD n = 0;
00035 BOOL ret = 0;
00036
00037 if (!_is_server || ConnectNamedPipe(_pipe,NULL))
00038 ret = WriteFile(_pipe,buffer,size,&n,NULL);
00039
00040 if (!ret)
00041 n = -1;
00042
00043 return (short)n;
00044 }
00045
00046 long
00047 NamedPipe::read(char*buffer, long size)
00048 {
00049 if (_pipe == NULL)
00050 return -1;
00051
00052 DWORD n = 0;
00053 BOOL ret = 0;
00054 if (!_is_server || ConnectNamedPipe(_pipe,NULL))
00055 ret = ReadFile(_pipe,buffer,size,&n,NULL);
00056
00057 if (!ret)
00058 n = -1;
00059 return n;
00060 }
00061
00062 void
00063 NamedPipe::flush()
00064 {
00065 if (_pipe == NULL)
00066 return;
00067
00068 FlushFileBuffers(_pipe);
00069 }
00070
00071 int
00072 NamedPipe::create(const char* name, int mode, long timeout)
00073 {
00074 char pname[NPIPE_MAXSZ];
00075 sprintf(pname, "%s%s", NPIPE_PREFIX, name);
00076
00077 _is_server = 1;
00078 DWORD access_mode = 0;
00079 if (mode & NPIPE_READ)
00080 access_mode |= PIPE_ACCESS_INBOUND;
00081 if (mode & NPIPE_WRITE)
00082 access_mode |= PIPE_ACCESS_OUTBOUND;
00083
00084 if (timeout == -1)
00085 timeout = 10000;
00086
00087 _pipe = CreateNamedPipe(pname,
00088 access_mode,
00089 PIPE_TYPE_BYTE|PIPE_READMODE_BYTE|PIPE_WAIT,
00090 1,
00091 4000, 4000,
00092 timeout,
00093 NULL);
00094
00095 if (_pipe == NULL || _pipe == INVALID_HANDLE_VALUE)
00096 return -1;
00097
00098 return 0;
00099 }
00100
00101 int
00102 NamedPipe::connect(const char* name, int mode, long timeout)
00103 {
00104 char pname[NPIPE_MAXSZ];
00105 sprintf(pname, "%s%s", NPIPE_PREFIX, name);
00106
00107 _is_server = 0;
00108 DWORD access_mode = 0;
00109 if (mode & NPIPE_READ)
00110 access_mode |= GENERIC_READ;
00111 if (mode & NPIPE_WRITE)
00112 access_mode |= GENERIC_WRITE;
00113
00114 short tries = 0;
00115 do {
00116 _pipe = CreateFile(pname,access_mode,0,NULL,OPEN_EXISTING,0,NULL);
00117 tries ++;
00118 }
00119 while((_pipe==NULL || _pipe == INVALID_HANDLE_VALUE) &&
00120 (timeout != -1) && (Sleep(timeout/10), tries <= 10));
00121
00122 if (_pipe == NULL || _pipe == INVALID_HANDLE_VALUE)
00123 return -1;
00124
00125 return 0;
00126 }
00127