Add to git.
[pthrlib.git] / doc / eg_echo.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <sys/socket.h>
4
5 #include <pool.h>
6
7 #include <pthr_pseudothread.h>
8 #include <pthr_iolib.h>
9 #include <pthr_server.h>
10
11 static void start_processor (int sock, void *data);
12 static void run (void *);
13
14 typedef struct processor_thread
15 {
16   pseudothread pth;             /* Pseudothread handle. */
17   int sock;                     /* Socket. */
18 } *processor_thread;
19
20 int
21 main (int argc, char *argv[])
22 {
23   /* Start up the server. */
24   pthr_server_main_loop (argc, argv, start_processor);
25
26   exit (0);
27 }
28
29 static void
30 start_processor (int sock, void *data)
31 {
32   pool pool;
33   processor_thread p;
34
35   pool = new_pool ();
36   p = pmalloc (pool, sizeof *p);
37
38   p->sock = sock;
39   p->pth = new_pseudothread (pool, run, p, "processor thread");
40
41   pth_start (p->pth);
42 }
43
44 static void
45 run (void *vp)
46 {
47   processor_thread p = (processor_thread) vp;
48   io_handle io;
49   char buffer[256];
50
51   io = io_fdopen (p->pth, p->sock);
52
53   /* Sit in a loop reading strings and echoing them back. */
54   while (io_fgets (buffer, sizeof buffer, io, 1))
55     io_fputs (buffer, io);
56
57   io_fclose (io);
58
59   pth_exit (p->pth);
60 }