]> mj.ucw.cz Git - libucw.git/blob - ucw/main-test.c
Main: Tests now include main_cleanup()
[libucw.git] / ucw / main-test.c
1 /*
2  *      UCW Library -- Main Loop: Testing
3  *
4  *      (c) 2004--2011 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include "ucw/lib.h"
11 #include "ucw/mainloop.h"
12
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <unistd.h>
16
17 #ifdef TEST
18
19 static struct main_process mp;
20 static struct main_block_io fin, fout;
21 static struct main_hook hook;
22 static struct main_timer tm;
23 static struct main_signal sg;
24 static int sig_counter;
25
26 static byte rb[16];
27
28 static void dread(struct main_block_io *bio)
29 {
30   if (bio->rpos < bio->rlen)
31     {
32       msg(L_INFO, "Read EOF");
33       block_io_del(bio);
34     }
35   else
36     {
37       msg(L_INFO, "Read done");
38       block_io_read(bio, rb, sizeof(rb));
39     }
40 }
41
42 static void derror(struct main_block_io *bio, int cause)
43 {
44   msg(L_INFO, "Error: %m !!! (cause %d)", cause);
45   block_io_del(bio);
46 }
47
48 static void dwrite(struct main_block_io *bio UNUSED)
49 {
50   msg(L_INFO, "Write done");
51 }
52
53 static int dhook(struct main_hook *ho UNUSED)
54 {
55   msg(L_INFO, "Hook called");
56   if (sig_counter >= 3)
57     return HOOK_SHUTDOWN;
58   return 0;
59 }
60
61 static void dtimer(struct main_timer *tm)
62 {
63   msg(L_INFO, "Timer tick");
64   timer_add_rel(tm, 11000);
65   timer_add_rel(tm, 10000);
66 }
67
68 static void dentry(void)
69 {
70   log_fork();
71   msg(L_INFO, "*** SUBPROCESS START ***");
72   sleep(2);
73   msg(L_INFO, "*** SUBPROCESS FINISH ***");
74   exit(0);
75 }
76
77 static void dexit(struct main_process *pr)
78 {
79   msg(L_INFO, "Subprocess %d exited with status %x", pr->pid, pr->status);
80 }
81
82 static void dsignal(struct main_signal *sg UNUSED)
83 {
84   msg(L_INFO, "SIGINT received (send 3 times to really quit, or use Ctrl-\\)");
85   sig_counter++;
86 }
87
88 int
89 main(void)
90 {
91   log_init(NULL);
92   main_init();
93
94   fin.read_done = dread;
95   fin.error_handler = derror;
96   block_io_add(&fin, 0);
97   block_io_read(&fin, rb, sizeof(rb));
98
99   fout.write_done = dwrite;
100   fout.error_handler = derror;
101   block_io_add(&fout, 1);
102   block_io_write(&fout, "Hello, world!\n", 14);
103
104   hook.handler = dhook;
105   hook_add(&hook);
106
107   tm.handler = dtimer;
108   timer_add_rel(&tm,  1000);
109
110   sg.signum = SIGINT;
111   sg.handler = dsignal;
112   signal_add(&sg);
113
114   mp.handler = dexit;
115   if (!process_fork(&mp))
116     dentry();
117
118   main_debug();
119
120   main_loop();
121   msg(L_INFO, "Finished.");
122
123   block_io_del(&fin);
124   block_io_del(&fout);
125   hook_del(&hook);
126   signal_del(&sg);
127   main_cleanup();
128   return 0;
129 }
130
131 #endif