File: sighands_test.cpp

package info (click to toggle)
libassa 3.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 3,084 kB
  • ctags: 2,323
  • sloc: cpp: 15,641; sh: 8,704; makefile: 372; perl: 51
file content (677 lines) | stat: -rw-r--r-- 19,428 bytes parent folder | download | duplicates (3)
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
// -*- c++ -*-
//------------------------------------------------------------------------------
//                          sighands_test.cpp
//------------------------------------------------------------------------------
// $Id: sighands_test.cpp,v 1.9 2006/07/20 02:30:56 vlg Exp $
//------------------------------------------------------------------------------
const char title [] =
"                                                                           \n"\
"  NAME                                                                     \n"\
"                                                                           \n"\
"     sighands_test                                                         \n"\
"                                                                           \n"\
"  DESCRIPTION                                                              \n"\
"                                                                           \n"\
"       Test program for following classes:                                 \n"\
"            o SigHandlers                                                  \n"\
"            o SigHandlersList                                              \n"\
"            o Semaphore                                                    \n"\
"                                                                           \n"\
"  Test progress is displayed to the standard output and appended to        \n"\
"  the test log file assa_tests.log.                                        \n"\
"                                                                           \n"\
"  Program runs through all test cases regardless of whether they ended     \n"\
"  with success or an error.                                                \n"\
"                                                                           \n"\
"  RETURN                                                                   \n"\
"                                                                           \n"\
"       0 on success, 1 if at least one test failed.                        \n"\
"                                                                           \n"\
"  SYNOPSIS                                                                 \n"\
"                                                                           \n"\
"       % sighands_test [OPTIONS]                                           \n"\
"                                                                           \n"\
"  OPTIONS                                                                  \n"\
"                                                                           \n"\
" -D, --log-file NAME - debug logging file name                             \n"\
" -v, --version         - print out version number                          \n"\
" -h, --help            - print out this help information                   \n"\
"                                                                           \n"\
"  Author: Vladislav Grinchenko                                             \n"\
"  Date:   Jul 12, 2000                                                     \n";
//------------------------------------------------------------------------------



#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <stdio.h>

#include <stdlib.h>

#include <fstream>		// ofstream
#include <iostream>
#include <string> 
#include <list>
using std::list;
using std::string;
using namespace std;

#if !defined (WIN32)

#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/wait.h>

#include "assa/GenServer.h"
#include "assa/Fork.h"
#include "assa/Assure.h"
#include "assa/Handlers.h"
#include "assa/Semaphore.h"
using namespace ASSA;

//------------------------------------------------------------------------------
// Global "C" signal handler and counter

int usr1_C_sig_count = 0;

extern "C" {
	static void usr1_C_handler (int signum_)
	{
		trace("usr1_C_handler");
	
		Assure_exit (signum_ == SIGUSR1);
		++usr1_C_sig_count;
    
		DL((TRACE,"<== Received SIG USR1 # %d\n", usr1_C_sig_count));
	}
};

class Test;

//------------------------------------------------------------------------------

class Child : public EventHandler
{
public:
    Child (Test* test_, long mask_);
    virtual       ~Child ();
    
    void          run           ();
    virtual int   handle_signal (int signum_);
    
private:
    sig_atomic_t  m_rcv_usr1_cnt;
    sig_atomic_t  m_rcv_usr2_cnt;
    Test*         m_test;
};

//------------------------------------------------------------------------------

class Test : public GenServer, public Singleton<Test>
{
public:
    Test ();
    ~Test ();

    virtual void  init_service    ();
    virtual void  process_events ();
    
    Semaphore&    get_semaphore () { return m_sem; }
    
    int           status () { return m_status; }

private:
    void          set_semaphore ();
    void          log_status (string& );
    void          catch_signals ();
    void          catch_signals_2 ();

    void          run_test1 ();
    void          run_test2 ();
    void          run_test3 ();
    void          run_test4 ();
    void          run_test5 ();
	
private:
    pid_t          m_child_pid;
    Child*         m_child;

    SIGUSR1Handler m_usr1;	// USER1 signal handlers
    Semaphore      m_sem;	// Semaphore
    int            m_status; // Program return status (0:ok, 1:error)
};

ASSA_DECL_SINGLETON(Test);

//------------------------------------------------------------------------------
//
// Start Class Child member functions
//   ||
//------------------------------------------------------------------------------

Child::Child (Test* test_, long mask_) 
	: m_rcv_usr1_cnt (0), m_rcv_usr2_cnt (0), m_test (test_)
{
    /*
      The child process is waiting indefinitely for USR1/USR2 signal, 
      and, upon reception of that signal, sends back 3 signals in a
      sequence with delay of one second to its parent process.
      
      The child process will be SIGTERMed by parent process upon 
      completion of its testing procedures.
    */
    
    /*--- Close parent's log file and open my own. ---*/
    Log::log_close ();

    /*--- 
      It took me 3 days to figure this one out! 
      If old log file is not around it's not a big deal. I used to call
      Assure_exit (unlink ()) here, and OS would send SIGHUP to
      the child process, loosing log message about assertion failed
      somehow, so that I didn't see it in the log file (either parent's
      or child's)!!! 07/18/2000
      ---*/

    unlink ("sighands_chld.log");

    Log::open_log_file ("sighands_chld.log", mask_);
    trace("Child::Child");

    DL((TRACE,"Parent's     PID: %d\n", getppid () ));
    DL((TRACE,"My (child's) PID: %d\n", getpid () ));

    SigHandlers& sh = m_test->get_sig_manager ();

    /*--- Block SIGHUP while processing SIGUSR1/SIGUSR2 ---*/
    SigSet bs;
    bs.add (SIGHUP);
    SigAction bact;
    bact.mask (bs);
	
    /*--- Install signal handler ---*/
    Assure_exit (sh.install (SIGUSR1, this, &bact) == 0);
    DL((TRACE,"SIGUSR1 signal handler installed!\n"));

	Assure_exit (sh.install (SIGUSR2, this, &bact) == 0);
	DL((TRACE,"SIGUSR2 signal handler installed!\n"));
}

Child::~Child ()
{
    trace("Child::~Child");
}

int
Child::handle_signal (int signum_)
{
    trace("Child::handle_signal");

    /*
	  Whatever signal is received will be reflected with 
	  a series of 3 similar signals back to parent process.
	*/
    Assure_exit (signum_ == SIGUSR1 || signum_ == SIGUSR2);

    DL((TRACE,"==> Rcvd %s (# %d) from Parent\n",
		(signum_ == SIGUSR1) ? "SIGUSR1" : "SIGUSR2",
		(signum_ == SIGUSR1) ? ++m_rcv_usr1_cnt : ++m_rcv_usr2_cnt));

    DL((TRACE," === Signal sequence started ===\n"));

    for (int i=0; i < 3; ++i) {
		kill (getppid (), signum_);
		sleep (1);
		DL((TRACE,"<== Sent %s (# %d) to the parent\n",
			(signum_ == SIGUSR1) ? "SIGUSR1" : "SIGUSR2", i));
    }
    DL((TRACE," === Signal sequence completed ===\n"));
    return 0;
}

void
Child::run ()
{
    trace("Child::run");
	
    /*--- Raise binary semaphore ---*/
    m_test->get_semaphore ().signal ();

    /*--- Let Reactor run processing all events (signals in our case) ---*/
    DL((TRACE," *** Running child ***\n"));

    while (m_test->service_is_active ()) {
		m_test->get_reactor ()->waitForEvents ();
    }
    DL((TRACE," *** Child exited main event loop ***\n"));
}

//------------------------------------------------------------------------------
//  ||
// End Class Child member functions
//
//------------------------------------------------------------------------------


//------------------------------------------------------------------------------
//  
// Start Class Test
//   ||
//------------------------------------------------------------------------------

Test::Test() : m_child_pid (0), m_child (NULL), m_status (0)
{
    trace("Test::Test");

    /* Set up a shared semaphore between parent and
       child. Child will inform Parent via this semaphore 
       that it is ready to receive commands (USR2 signals) from it.
       
       With no semaphore in place, parent is forced to sleep before sending
       command signal. Otherwise the signal could have been emitted before
       child had had a chance to install its signal handler.
    */

    set_semaphore ();
}

void 
Test::set_semaphore ()
{
    trace("Test::set_semaphore");

    /*
      Set up a semaphore. In a parent-child relationship, the parent
      creates new IPC structure and the resulting identifier is then
      available to the child after the 'fork(2)'.
      
      We use debug file name as assured file, and 's' as project 
      identifier.
    */

    key_t key = ftok ("/etc/hosts", 'S');
    Assure_exit (key != (key_t)-1);

    /*--- Create semaphore ---*/
    Assure_exit (m_sem.create (key, 0) != -1);
    m_sem.dump ();
}

Test::~Test() 
{
    trace("Test::~Test");

    m_sem.close ();
    
    if (m_child != NULL) {
		delete m_child;
    }
}

void 
Test::init_service ()
{
    trace("Test::init_service");

    /* Fork a child process - it will send us signals */

    DL((TRACE," Forking child process ...\n"));

    Fork ss (Fork::KILL_ON_EXIT, Fork::IGNORE_STATUS);

    if (ss.isChild ()) {
		m_child = new Child (this, m_mask);
		m_child->run ();
		DL((TRACE," *** Child stopped ***\n"));
		exit (0);
    }
    DL((TRACE," Forking completed!\n"));

    m_child_pid = ss.getChildPID ();
    DL((TRACE," Child's PID: %d\n", m_child_pid));

    
    /*--- Write header to the log file ---*/
    std::cout << "\n============== sighands_test ==================\n"
			  << "\nTesting classes: SigHandlers, SigHandlersList, "
			  << "Semaphore\n";
}

void 
Test::process_events ()
{
    trace("Test::process_events");

    /*--- Block waiting for child to signal on the semaphore ---*/
    m_sem.wait ();
	
    /*--- Run tests ---*/
    run_test1 ();
    run_test2 ();

    run_test3 ();
    run_test4 ();
    run_test5 ();
	
    /*--- Complete log record ---*/
    std::cout << "\n============== sighands_test completed ========\n";
}


void 
Test::log_status (string& m_)
{
    trace("Test::log_status");
    std::cout << m_ << flush;
    DL((TRACE," %s\n", m_.c_str ()));
}

void 
Test::catch_signals ()
{
    trace("Test::catch_signals");

    /* Send USR1 signal to child for triggering a signal sequence from it. */
    DL((TRACE,"Sending SIGUSR1 to child process PID: %d ==>\n", m_child_pid));

    Assure_exit (kill (m_child_pid, SIGUSR1) == 0);

    /*--- Wait for all signals for the total of 5 seconds. ---*/
    DL((TRACE," Waiting for 5 seconds on child ...\n"));
    TimeVal tv (5.0);   

    while (tv != TimeVal::zeroTime ()) {
		get_reactor ()->waitForEvents (&tv);
    }
}
void 
Test::catch_signals_2 ()
{
    trace("Test::catch_signals");

    /* Send USR1 signal to child for triggering a signal sequence from it. */
    DL((TRACE,"Sending SIGUSR1 to child process PID: %d ==>\n", m_child_pid));

    Assure_exit (kill (m_child_pid, SIGUSR1) == 0);
    
    /* Send USR2 signal to child for triggering a signal sequence from it. */
    DL((TRACE,"Sending SIGUSR2 to child process PID: %d ==>\n",m_child_pid));

    Assure_exit (kill (m_child_pid, SIGUSR2) == 0);

    /* Wait for 6 signals for the total of 10 seconds (to be on a safe side) */
    DL((TRACE," Waiting for 5 seconds on child ...\n"));

    TimeVal tv (10.0);   

    while (tv != TimeVal::zeroTime ()) {
		get_reactor ()->waitForEvents (&tv);
    }
}

void
Test::run_test1 ()
{
    /*-------------------------------------------------------------------
      Test 1: Testing "C" handler.
      ---------------------------------------------
      + Install conventional "C" handler simulating presence of 3rd party 
      handler situation.
      + Receive 3 signals from child process and validate the count.
      -------------------------------------------------------------------*/
    trace("Test::run_test1");

    DL((TRACE,"=== Test 1 started ===\n"));

    SigAction oact;
    SigAction act (&usr1_C_handler);
    
    usr1_C_sig_count = 0;
    act.register_action (SIGUSR1, &oact);

    catch_signals ();

    string status_msg ("=== Test 1 ");
    if (usr1_C_sig_count != 3) {
		status_msg += " failed (count != 3) ===\n";
		m_status = 1;
    }
    else {
		status_msg += " ok ===\n";
    }
    log_status (status_msg);
}

void
Test::run_test2 ()
{
    /*-------------------------------------------------------------------
      Test 2: Testing EventHandler & "C" handler dispatched through
      signal dispatcher.
      ---------------------------------------------
      + Install SIGUSR1 EventHandler
      + Receive signals.
      + Validate that all 3 signals have been captured by the "C" handler.
      -------------------------------------------------------------------*/
    trace("Test::run_test2");

    DL((TRACE,"=== Test 2 started ===\n"));

    /* 
       Install USR1 signal handler. 'Test' is EventHandler and will
       catch signals itself.
    */
    usr1_C_sig_count = 0;
    m_usr1.resetState ();
    m_sig_dispatcher.install (SIGUSR1, &m_usr1);
    
    catch_signals ();
    
    string status_msg = "=== Test 2  ok ===\n";
    bool failed = false;
    
    if (m_usr1.received_count () != 3) {
		status_msg = "=== Test 2  failed on USR1 (count != 3) ===\n";
		log_status (status_msg);
		failed = true;
    }
    
    if (usr1_C_sig_count  != 3) {
		status_msg = "=== Test 2  failed on \"C\" handler";
		status_msg += "(count != 3) ===\n";
		log_status (status_msg);
		failed = true;
    }
	
    if (!failed) {
		log_status (status_msg);
    }
    else {
		m_status = 1;
    }
}

void
Test::run_test3 ()
{
    /*-------------------------------------------------------------------
      Test 3: Validate preservation of 
      ---------------------------------------------
      + Remove SIG USR1 Event Handler.
      + Receive signals.
      + Validate that "C" handler still received all signals.
      -----------------------------------------------------------------*/
    trace("Test::run_test3");

    DL((TRACE,"=== Test 3 started ===\n"));
    m_usr1.resetState ();
    usr1_C_sig_count = 0;
    
    m_sig_dispatcher.remove (SIGUSR1, &m_usr1);
    
    catch_signals ();
    
    string status_msg ("=== Test 3 ");
	
    if (usr1_C_sig_count != 3) {
		status_msg += " failed (count != 3) ===\n";
		m_status = 1;
    }
    else {
		status_msg += " ok ===\n";
    }
    log_status (status_msg);
}

void
Test::run_test4 ()
{
    /*-------------------------------------------------------------------
      Test 4: Test preservance of 3rd party signal handler
      even after signal dispatcher is deactivated.
      ---------------------------------------------
      + Clean up signal dispatcher
      + Receive signals
      + Validate that "C" handler still received all signals.
      ---------------------------------------------------------------------*/
    trace("Test::run_test4");

    DL((TRACE,"=== Test 4 started ===\n"));

    usr1_C_sig_count = 0;
    
    catch_signals ();
    
    string status_msg ("=== Test 4 ");
	
    if (usr1_C_sig_count != 3) {
		status_msg += " failed (count != 3) ===\n";
		m_status = 1;
    }
    else {
		status_msg += " ok ===\n";
    }
    log_status (status_msg);
}

void
Test::run_test5 ()
{
    /*-------------------------------------------------------------------
      Test 5: Test mulitpe signals with multiple Event Handlers.
      ---------------------------------------------
      + Install 20 usr1 and usr2 event handlers 
      + Receive both usr1 and usr2 signals.
      + Validate that "C" handler still received all signals,
      and all event handlers received all of the signals
      ---------------------------------------------------------------------*/
    trace("Test::run_test5");

    register int i;
    register SIGUSR1Handler* h1p;
    register SIGUSR2Handler* h2p;
    const int SN = 1;
    
    list<SIGUSR1Handler*> usr1_list;
    list<SIGUSR2Handler*> usr2_list;
    
    DL((TRACE,"=== Test 5 started ===\n"));
    
    /*--- Reset C handler count ---*/
    usr1_C_sig_count = 0;
    
    /*--- Create and install 20 USR1 signals ---*/
    for (i=0; i<SN; i++) {
		h1p = new SIGUSR1Handler;
		Assure_exit (m_sig_dispatcher.install (SIGUSR1, h1p) == 0);
		usr1_list.push_back (h1p);
    }
    
    /*--- Create and install 20 USR2 signals ---*/
    for (i=0; i<SN; i++) {
		h2p = new SIGUSR2Handler;
		Assure_exit (m_sig_dispatcher.install (SIGUSR2, h2p) == 0);
		usr2_list.push_back (h2p);
    }
    
    /*--- Catch all signals ---*/
    catch_signals_2 ();
    
    /*--- Count signals ---*/
    bool seen_error = false;
    bool failed = false;
    string status_msg ("=== Test 5  ok ===\n");
    
    /*--- Test counters ---*/
    while (!usr1_list.empty ()) {
		h1p = usr1_list.front ();

		if (h1p->received_count () != 3) {
			seen_error = true, failed = true;
			status_msg = "=== Test 5  failed: USR1 rcvd signals";
			status_msg += "count != 3 ===\n";
		}
		Assure_exit (m_sig_dispatcher.remove (SIGUSR1, h1p) == 0);
		usr1_list.pop_front ();
		delete h1p;
    }
    if (seen_error) log_status (status_msg);
    
    while (!usr2_list.empty ()) {
		h2p = usr2_list.front ();
		if (h2p->received_count () != 3) {
			seen_error = true, failed = true;
			status_msg = "=== Test 5  failed: USR2 rcvd signals";
			status_msg += "count != 3 ===\n";
		}
		Assure_exit (m_sig_dispatcher.remove (SIGUSR2, h2p) == 0);
		usr2_list.pop_front ();
		delete h2p;
    }
    if (seen_error) log_status (status_msg);
    
    if (usr1_C_sig_count != 3) {
		failed = true;
		status_msg = "=== Test 5  failed: \"C\" rcvd signals";
		status_msg += "count != 3 ===\n";
		log_status (status_msg);
    }
    
    if (!failed ) log_status (status_msg);
    else m_status = 1;
}

#endif	// !WIN32

//------------------------------------------------------------------------------
//   ||
// End Class Test
//   
//------------------------------------------------------------------------------

int main (int argc, char* argv[])
{
#if !defined (WIN32)

    int rev = 0;
    Test& t = *Test::get_instance ();
    
    t.set_version ("1.1", rev);
    t.set_author ("Vladislav Grinchenko");
    
    t.set_flags (GenServer::RMLOG);
    t.init (&argc, argv, title);

    t.init_service ();
    t.process_events ();
    
    exit (t.status ());

#else

	exit (0);

#endif
}