j'ai écrit un client/serveur utilisant les tubes nommés. Le serveur utilise l'overlapped I/O (je ne sais pas comment trraduire ceci). Je me suis inspiré beaucoup de [1] et [2] car je ne connais pas énormément de choses à propos des tubes nommés et des clients/serveurs. Voici mes codes:

Le serveur:
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/* gcc -g -Wall -o server.exe server2.c */

#include <stdio.h>

#include <windows.h>


#define BUFSIZE 512

typedef struct
{
  HANDLE pipe;
  OVERLAPPED ol;

  /* in normal struct */
  void *data;
  int size;
} Server;

void print_last_error(const char *fct) 
{
  char *buf;
  DWORD dw = GetLastError(); 

  FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | 
                FORMAT_MESSAGE_FROM_SYSTEM |
                FORMAT_MESSAGE_IGNORE_INSERTS,
                NULL,
                dw,
                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                (LPTSTR) &buf,
                0, NULL );

    // Display the error message and exit the process

  printf("%s failed with error %ld: %s\n", fct, dw, buf);
  LocalFree(buf); 
}

Server *
server_new(const char *name)
{
  char buf[256];
  Server *svr;
  HANDLE event;
  BOOL res;

  if (!name)
    return NULL;

  svr = (Server *)calloc(1,sizeof(Server));
  if (!svr)
    return NULL;

  snprintf(buf, sizeof(buf), "\\\\.\\pipe\\%s", name);

  /*
   * Asynchronuous
   * block mode
   */
  svr->pipe = CreateNamedPipe(buf,
                              PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
                              PIPE_UNLIMITED_INSTANCES,
                              BUFSIZE,
                              BUFSIZE,
                              5000,
                              NULL);
  if (!svr->pipe)
    {
      print_last_error("CreateNamedPipe");
      goto free_svr;
    }

  /*
   * Manual reset
   * Initial state : non signaled
   */
  event = CreateEvent(NULL, TRUE, FALSE, NULL);
  if (!event)
    {
      print_last_error("CreateEvent");
      goto close_pipe;
    }

  memset(&svr->ol, 0, sizeof(svr->ol));
  svr->ol.hEvent = event;

  res = ConnectNamedPipe(svr->pipe, &svr->ol);
  if (res)
    {
      print_last_error("ConnectNamedPipe");
      goto close_event;
    }
  else
    {
      DWORD err = GetLastError();

      if (err == ERROR_PIPE_CONNECTED)
        {
          SetEvent(svr->ol.hEvent);
          printf("client connected\n");
        }
      else if (err != ERROR_IO_PENDING)
        {
          print_last_error("ConnectNamedPipe");
          goto close_event;
        }
      /* else, we have ERROR_IO_PENDING, so a connection link is pending */
    }

  return svr;

 close_event:
  CloseHandle(event);
 close_pipe:
  CloseHandle(svr->pipe);
 free_svr:
  free(svr);

  return NULL;
}

void
server_del(Server *svr)
{
  if (!svr)
    return;

  if (!FlushFileBuffers(svr->pipe))
    {
      print_last_error("FlushFileBuffers");
    }
  if (!DisconnectNamedPipe(svr->pipe))
    {
      print_last_error("DisconnectNamedPipe");
    }
  CloseHandle(svr->ol.hEvent);
  CloseHandle(svr->pipe);
  free(svr);
}

void
server_data_send(Server *svr, const void *data, int size)
{
  OVERLAPPED ol;
  DWORD to_write;
  DWORD written;

  if (!svr || !data || (size <= 0))
    return;

  memset(&ol, 0, sizeof(svr->ol));
  ol.hEvent = svr->ol.hEvent;

  while (size > 0)
    {
      if (size <= 65535)
        {
          to_write = size;
          size = 0;
        }
      else
        {
          to_write = 65535;
          size -= 65535;
        }

      if (!WriteFile(svr->pipe, data, to_write, &written, &svr->ol))
        {
          DWORD ret = GetLastError();

          if (ret != ERROR_IO_PENDING)
            {
              print_last_error("WriteFile");
              break;
            }
          else
            continue;
        }

      data += to_write;

      /* should never happen */
      if (written < to_write)
        {
          printf("WriteFile: insufficient buffer space\n");
        }
    }
}

void
server_data_get(Server *svr)
{
  char buf[BUFSIZE];
  OVERLAPPED ol;
  void *data = NULL;
  DWORD nbr_bytes_read;
  int size = 0;
  BOOL res;

  if (!svr)
    return;

  memset(&ol, 0, sizeof(ol));
  ol.hEvent = svr->ol.hEvent;

  do
    {
      res = ReadFile(svr->pipe, buf, sizeof(buf), &nbr_bytes_read, &ol);
      if (res || (!res && (GetLastError() == ERROR_IO_PENDING)))
        {
          if (nbr_bytes_read > 0)
            {
              if (!data)
                {
                  data = malloc(nbr_bytes_read);
                  if (!data)
                    break;
                  memcpy(data, buf, nbr_bytes_read);
                  size = nbr_bytes_read;
                }
              else
                {
                  data = realloc(data, size + nbr_bytes_read);
                  if (!data)
                    {
                      size = 0;
                      break;
                    }
                  memcpy(data + size, buf, nbr_bytes_read);
                  size += nbr_bytes_read;
                }
            }
        }
      else if (!res && (GetLastError() != ERROR_MORE_DATA))
        {
          print_last_error("ReadFile");
          /* we keep current read data ? (i.e. no free(data) ? ) */
          break;
        }
      /* else ERROR_MORE_DATA and we continue to loop */
    }
  while (!res);

  svr->data = data;
  svr->size = size;
}

int main()
{
  Server *svr;
  DWORD ret;
  DWORD nbr_bytes;
  BOOL res;

  svr = server_new("toto");
  if (!svr)
    return -1;

  printf("waiting for client...\n");

  while (1)
    {
      ret = WaitForMultipleObjects(1, &svr->ol.hEvent, FALSE, INFINITE);
      if (ret == WAIT_FAILED)
        {
          print_last_error("WaitForMultipleObjects");
          goto beach;
        }

      ResetEvent(svr->ol.hEvent);

      res = GetOverlappedResult(svr->pipe, &svr->ol,
                                &nbr_bytes, FALSE);
      if (!res)
        {
          print_last_error("GetOverlappedResult");

          if (!DisconnectNamedPipe(svr->pipe))
            {
              print_last_error("DisconnectNamedPipe");
              goto beach;
            }

          res = ConnectNamedPipe(svr->pipe, &svr->ol);
          if (res)
            {
              print_last_error("ConnectNamedPipe");
              goto beach;
            }
          else
            {
              DWORD err = GetLastError();

              if (err == ERROR_PIPE_CONNECTED)
                {
                  SetEvent(svr->ol.hEvent);
                }
              else if (err != ERROR_IO_PENDING)
                {
                  print_last_error("ConnectNamedPipe");
                  goto beach;
                }
              /* else, we have ERROR_IO_PENDING, so a connection link is pending */
            }
        }
      else
        {
          printf("client connected\n");
          server_data_get(svr);
          if (svr->data)
            {
              char *buf;
              buf = malloc(svr->size + 1);
              memcpy(buf, svr->data, svr->size);
              buf[svr->size] = '\0';
              printf("server (%d) : %s\n", svr->size, buf);
              free(svr->data);
              svr->data = NULL;
            }
          server_data_send(svr, "salut, c'est le serveur !!", strlen("salut, c'est le serveur !!"));
        }
    }

 beach:
  server_del(svr);

  return 0;
}
et le client :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
/* gcc -g -Wall -o client.exe client2.c */

#include <stdio.h>
#include <string.h>

#include <windows.h>

void print_last_error(const char *fct) 
{
  char *buf;
  DWORD dw = GetLastError(); 

  FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | 
                FORMAT_MESSAGE_FROM_SYSTEM |
                FORMAT_MESSAGE_IGNORE_INSERTS,
                NULL,
                dw,
                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                (LPTSTR) &buf,
                0, NULL );

    // Display the error message and exit the process

  printf("%s failed with error %ld: %s\n", fct, dw, buf);
  LocalFree(buf); 
}


typedef struct
{
  HANDLE pipe;
  OVERLAPPED ol;

  /* in normal struct */
  void *data;
  int size;
} Server;

Server *
server_new(const char *name)
{
  char buf[256];
  Server *svr;

  if (!name)
    return NULL;

  printf("connecting to server...");

  snprintf(buf, sizeof(buf), "\\\\.\\pipe\\%s", name);

  svr = (Server *)calloc(1, sizeof(Server));
  if (!svr)
    return NULL;

  while (1)
    {
      svr->pipe = CreateFile(buf,
                             GENERIC_READ | GENERIC_WRITE,
                             0,
                             NULL,
                             OPEN_EXISTING,
                             0,
                             NULL);
      if (svr->pipe != INVALID_HANDLE_VALUE)
        break;

      /* if pipe not busy, we exit */
      if (GetLastError() != ERROR_PIPE_BUSY)
        {
          print_last_error("CreateFile");
          goto free_svr;
        }

      /* pipe busy, so we wait for it */
      if (!WaitNamedPipe(buf, NMPWAIT_WAIT_FOREVER))
        {
          print_last_error("WaitNamedPipe");
          goto close_pipe;
        }
    }

  printf(" done\n");

  return svr;

 close_pipe:
  CloseHandle(svr->pipe);
 free_svr:
  free(svr);

  printf(" failed\n");
  return NULL;
}

void
server_del(Server *svr)
{
  if (!svr)
    return;

  CloseHandle(svr->pipe);
  free(svr);
}

void
server_data_send(Server *svr, const void *data, int size)
{
  DWORD to_write;
  DWORD written;

  if (!svr || !data || (size <= 0))
    return;

  while (size > 0)
    {
      if (size <= 65535)
        {
          to_write = size;
          size = 0;
        }
      else
        {
          to_write = 65535;
          size -= 65535;
        }

      if (!WriteFile(svr->pipe, data, to_write, &written, NULL))
        {
          print_last_error("WriteFile");
          break;
        }

      data += to_write;

      /* should never happen */
      if (written < to_write)
        {
          printf("WriteFile: insufficient buffer space\n");
        }
    }
}

void
server_data_get(Server *svr)
{
#define BUFSIZE 512
  char buf[BUFSIZE];
  void *data = NULL;
  DWORD nbr_bytes_read;
  int size = 0;
  BOOL res;

  if (!svr)
    return;

  do
    {
      res = ReadFile(svr->pipe, buf, sizeof(buf), &nbr_bytes_read, NULL);
      if (!res)
        {
          if (GetLastError() == ERROR_MORE_DATA)
            continue;
          else
            {
              print_last_error("ReadFile");
              /* we keep current read data ? (i.e. no free(data) ? ) */
              break;
            }
        }
      if (res && (nbr_bytes_read > 0))
        {
          if (!data)
            {
              data = malloc(nbr_bytes_read);
              if (!data)
                break;
              memcpy(data, buf, nbr_bytes_read);
              size = nbr_bytes_read;
            }
          else
            {
              data = realloc(data, size + nbr_bytes_read);
              if (!data)
                {
                  size = 0;
                  break;
                }
              memcpy(data + size, buf, nbr_bytes_read);
              size += nbr_bytes_read;
            }
        }
    }
  while (!res);

  svr->data = data;
  svr->size = size;
}

int main(void)
{
  Server *svr;

  svr = server_new("toto");
  if (!svr)
    return -1;

  server_data_send(svr, "salut, c'est le client !", strlen("salut, c'est le client !"));

  while (1)
    {
      server_data_get(svr);
      if (svr->data)
        {
          char *buf;
          buf = malloc(svr->size + 1);
          memcpy(buf, svr->data, svr->size);
          buf[svr->size] = '\0';
          printf("client (%d) : %s\n", svr->size, buf);
          free(svr->data);
          svr->data = NULL;
          Sleep(5000);
          break;
        }
    }

  server_del(svr);

  return 0;
}
Donc, dans ces codes, quand je veux lire des données, je fais une boucle sur ReadFile() et j'attends que les données soient disponibles.

Je voudrais savoir s'il existe un moyen de savoir si des données sont disponibles avec WaitForMultipleObjects(), celle-ci retournant quand une donnée doit être lue, plutôt que de faire une bloucle sur ReadFile() (ce qui peut êter bloquant). Je précise au passage que je voudrais éviter de créer un thread.

Question assimilée : si on passe 0 au 3ème paramète (nNumberOfBytesToRead) de Readfile(), est-ce que celle-ci renvoie FALSE et GetLastError() renvoie ERROR_MORE_DATA ?

Merci

[1] http://msdn.microsoft.com/en-us/libr...8VS.85%29.aspx
[2] http://msdn.microsoft.com/en-us/libr...8VS.85%29.aspx