File: template.c

package info (click to toggle)
radlib 2.12.0-7
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 3,072 kB
  • sloc: ansic: 15,843; sh: 8,102; makefile: 498
file content (590 lines) | stat: -rw-r--r-- 15,773 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
/*---------------------------------------------------------------------------
 
  FILENAME:
        template.c
 
  PURPOSE:
        Provide the radlib template process entry point.
 
  REVISION HISTORY:
        Date            Engineer        Revision        Remarks
        01/01/2004      Your Name       0               Original
 
  NOTES:
        All references to "template" should be replaced by a meaningful
        process name, including the file names and data structures.
 
----------------------------------------------------------------------------*/

// System include files
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

// radlib include files

// Local include files
#include "template.h"


// global memory declarations

// global memory referenced

// static (local) memory declarations

// declare the process work area
static TEMPLATE_WORK    templateWork;

// define the configuration file IDs in use
enum ConfigIds
{
    CFG_ID_FILE_DEV         = 0,
    CFG_ID_VERBOSE_MODE     = 1
};

// and the corresponding string identifiers
static char             *configIDs[] =
{
    "FILE_DEV",
    "VERBOSE_MSGS"
};


// methods

static void msgHandler
(
    char        *srcQueueName,
    UINT        msgType,
    void        *msg,
    UINT        length,
    void        *userData
)
{
    STIM        stim;

    stim.type           = STIM_QMSG;
    stim.srcQueueName   = srcQueueName;
    stim.msgType        = msgType;
    stim.msg            = msg;
    stim.length         = length;

    radStatesProcess (templateWork.stateMachine, &stim);

    return;
}

static void evtHandler
(
    UINT        eventsRx,
    UINT        rxData,
    void        *userData
)
{
    STIM        stim;

    stim.type           = STIM_EVENT;
    stim.eventsRx       = eventsRx;
    stim.eventData      = rxData;

    radStatesProcess (templateWork.stateMachine, &stim);

    return;
}

static void timer1Handler (void *parm)
{
    STIM        stim;

    memset (&stim, 0, sizeof (stim));

    stim.type           = STIM_TIMER;
    stim.timerNumber    = TEMPLATE_TIMER_NUM1;

    radStatesProcess (templateWork.stateMachine, &stim);

    return;
}

static void timer2Handler (void *parm)
{
    STIM        stim;

    memset (&stim, 0, sizeof (stim));

    stim.type           = STIM_TIMER;
    stim.timerNumber    = TEMPLATE_TIMER_NUM2;

    radStatesProcess (templateWork.stateMachine, &stim);

    return;
}

static void stdinDataCallback (int fd, void *userData)
{
    STIM        stim;

    memset (&stim, 0, sizeof (stim));

    stim.type           = STIM_IO;
    stim.iofd           = fd;

    radStatesProcess (templateWork.stateMachine, &stim);

    return;
}


// process initialization
static int templateSysInit (void)
{
    char            devPath[256], temp[32];
    char            *installPath;
    struct stat     fileData;
    FILE            *pidfile;

    // get the install path
    installPath = getenv ("APPLICATION_RUN_DIRECTORY");
    if (installPath == NULL)
    {
        installPath = ".";
    }
    chdir (installPath);


    // check for our pid file, don't run if it is there
    sprintf (devPath, "%s/%s", installPath, TEMPLATE_LOCK_FILENAME);
    if (stat (devPath, &fileData) == 0)
    {
        printf ("lock file %s exists, older copy may be running - aborting!\n",
                devPath);
        return -1;
    }


    // create our device directory if it is not there
    sprintf (devPath, "%s/dev", installPath);
    if (stat (devPath, &fileData) != 0)
    {
        if (mkdir (devPath, 0755) != 0)
        {
            printf ("Cannot create device dir: %s - aborting!\n",
                    devPath);
            return -1;
        }
    }

    return 0;
}

// system exit
static int templateSysExit (void)
{
    char            devPath[256];
    char            *installPath;
    struct stat     fileData;

    // get the install path
    installPath = getenv ("APPLICATION_RUN_DIRECTORY");
    if (installPath == NULL)
    {
        installPath = ".";
    }

    // delete our pid file
    sprintf (devPath, "%s/%s", installPath, TEMPLATE_LOCK_FILENAME);
    if (stat (devPath, &fileData) == 0)
    {
        printf ("\nlock file %s exists, deleting it...\n",
                devPath);
        if (unlink (devPath) == -1)
        {
            printf ("lock file %s delete failed!\n",
                    devPath);
        }
    }

    return 0;
}

static void defaultSigHandler (int signum)
{
    switch (signum)
    {
        case SIGPIPE:
            // if you are using sockets or pipes, you will need to catch this
            // we have a far end socket disconnection, we'll handle it in the
            // "read/write" code
            signal (signum, defaultSigHandler);
            break;

        case SIGILL:
        case SIGBUS:
        case SIGFPE:
        case SIGSEGV:
        case SIGXFSZ:
        case SIGSYS:
            // unrecoverable signal - we must exit right now!
            radMsgLog(PRI_CATASTROPHIC, "templated: recv sig %d: bailing out!", signum);
            abort ();
        
        case SIGCHLD:
            wait (NULL);
            signal (signum, defaultSigHandler);
            break;

        default:
            // can we allow the process to exit normally?
            if (radProcessGetExitFlag())
            {
                // NO! - we gotta bail here!
                radMsgLog(PRI_HIGH, "templated: recv sig %d: exiting now!", signum);
                exit (0);                
            }
            
            // we can allow the process to exit normally...
            radMsgLog(PRI_HIGH, "templated: recv sig %d: exiting!", signum);
        
            radProcessSetExitFlag ();
        
            signal (signum, defaultSigHandler);
            break;
    }

    return;
}


// the main entry point for the template process
int main (int argc, char *argv[])
{
    void            (*alarmHandler)(int);
    STIM            stim;
    int             i;
    char            qname[256], cfgname[256], instance[32], value[32];
    char            pidName[256];
    char            *installPath;
    CF_ID           configFileId;
    struct stat     fileStatus;
    FILE            *pidfile;


    // initialize some system stuff first
    if (templateSysInit () == -1)
    {
        radMsgLogInit (PROC_NAME_TEMPLATE, TRUE, TRUE);
        radMsgLog(PRI_CATASTROPHIC, "system init failed!\n");
        radMsgLogExit ();
        exit (1);
    }

    // create some file paths for later use
    installPath = getenv ("APPLICATION_RUN_DIRECTORY");
    if (installPath == NULL)
    {
        installPath = ".";
    }
    sprintf (qname, "%s/dev/%s", installPath, PROC_NAME_TEMPLATE);
    sprintf (cfgname, "%s/%s", installPath, TEMPLATE_CONFIG_FILENAME);
    sprintf (pidName, "%s/%s", installPath, TEMPLATE_LOCK_FILENAME);

    memset (&templateWork, 0, sizeof (templateWork));



    // call the global radlib system init function
    if (radSystemInit (TEMPLATE_SYSTEM_ID) == ERROR)
    {
        radMsgLogInit (PROC_NAME_TEMPLATE, TRUE, TRUE);
        radMsgLog(PRI_CATASTROPHIC, "%s: radSystemInit failed!");
        radMsgLogExit ();
        exit (1);
    }


    // call the radlib process init function
    if (radProcessInit (PROC_NAME_TEMPLATE,
                        qname,
                        PROC_NUM_TIMERS_TEMPLATE,
                        FALSE,                     // FALSE => not as daemon
                        msgHandler,
                        evtHandler,
                        NULL)
            == ERROR)
    {
        radMsgLogInit (PROC_NAME_TEMPLATE, TRUE, TRUE);
        radMsgLog(PRI_CATASTROPHIC, "radProcessInit failed: %s",
                   PROC_NAME_TEMPLATE);
        radMsgLogExit ();

        radSystemExit (TEMPLATE_SYSTEM_ID);

        exit (1);
    }

    // save our process pid and create the lock file 
    templateWork.myPid = getpid ();
    pidfile = fopen (pidName, "w");
    if (pidfile == NULL)
    {
        radMsgLog(PRI_CATASTROPHIC, "lock file create failed!\n");

        radProcessExit ();
        radSystemExit (TEMPLATE_SYSTEM_ID);

        exit (1);
    }
    fprintf (pidfile, "%d", templateWork.myPid);
    fclose (pidfile);


    // save the current alarm signal handler, set all signal handlers
    // to the default handler, then set the alarm handler back to original
    alarmHandler = radProcessSignalGetHandler (SIGALRM);
    radProcessSignalCatchAll (defaultSigHandler);
    radProcessSignalCatch (SIGALRM, alarmHandler);


    // get our configuration values
    if (stat (cfgname, &fileStatus) == -1)
    {
        // file does not exist, populate with defaults
        configFileId = radCfOpen (cfgname);
        if (configFileId == NULL)
        {
            radMsgLog(PRI_CATASTROPHIC, "radCfOpen 1 failed!\n");

            radProcessExit ();
            radSystemExit (TEMPLATE_SYSTEM_ID);

            exit (1);
        }

        radCfPutEntry (configFileId,
                       configIDs[CFG_ID_FILE_DEV],
                       NULL,
                       "/dev/ttyS0",
                       "template serial device");
        radCfPutEntry (configFileId,
                       configIDs[CFG_ID_VERBOSE_MODE],
                       NULL,
                       "1",
                       "produce more and verbose diagnostics");

        // write out the new file
        if (radCfFlush (configFileId) == ERROR)
        {
            radMsgLog(PRI_CATASTROPHIC, "radCfFlush failed!\n");

            radProcessExit ();
            radSystemExit (TEMPLATE_SYSTEM_ID);

            exit (1);
        }

        radCfClose (configFileId);
    }


    // now open the config file for reading
    configFileId = radCfOpen (cfgname);
    if (configFileId == NULL)
    {
        radMsgLog(PRI_CATASTROPHIC, "radCfOpen 2 failed!\n");

        radProcessExit ();
        radSystemExit (TEMPLATE_SYSTEM_ID);

        exit (1);
    }

    if (radCfGetFirstEntry (configFileId,
                            configIDs[CFG_ID_FILE_DEV],
                            NULL,
                            value)
            == ERROR)
    {
        radMsgLog(PRI_CATASTROPHIC, "radCfGetFirstEntry failed!\n");
        radCfClose (configFileId);

        radProcessExit ();
        radSystemExit (TEMPLATE_SYSTEM_ID);

        exit (1);
    }
    strncpy (templateWork.fileDev, value, sizeof(templateWork.fileDev));

    if (radCfGetFirstEntry (configFileId,
                            configIDs[CFG_ID_VERBOSE_MODE],
                            NULL,
                            value)
            == ERROR)
    {
        radMsgLog(PRI_CATASTROPHIC, "radCfGetFirstEntry failed!\n");
        radCfClose (configFileId);

        radProcessExit ();
        radSystemExit (TEMPLATE_SYSTEM_ID);

        exit (1);
    }
    templateWork.verboseMode = atoi (value);

    radCfClose (configFileId);


    // open stdin and setup for "radProcessWait" calls
    // (stdin is already open, but other devices should be opened
    // prior to registration)
    if (radProcessIORegisterSTDIN (stdinDataCallback, NULL) == ERROR)
    {
        radMsgLog(PRI_HIGH, "IORegDescriptor failed");

        radProcessExit ();
        radSystemExit (TEMPLATE_SYSTEM_ID);

        exit (1);
    }

    radMsgLog(PRI_STATUS, "stdin 'opened' and registered ...");


    // create our state machine - where all run-time work is done
    templateWork.stateMachine = radStatesInit (&templateWork);
    if (templateWork.stateMachine == NULL)
    {
        radMsgLog(PRI_HIGH, "radStatesInit failed");

        radProcessExit ();
        radSystemExit (TEMPLATE_SYSTEM_ID);

        exit (1);
    }

    if (radStatesAddHandler (templateWork.stateMachine, TEMPLATE_STATE_IDLE,
                             templateIdleState)
            == ERROR)
    {
        radMsgLog(PRI_HIGH, "radStatesAddHandler failed");
        radStatesExit (templateWork.stateMachine);

        radProcessExit ();
        radSystemExit (TEMPLATE_SYSTEM_ID);

        exit (1);
    }
    if (radStatesAddHandler (templateWork.stateMachine, TEMPLATE_STATE_RUN,
                             templateRunState)
            == ERROR)
    {
        radMsgLog(PRI_HIGH, "radStatesAddHandler failed");
        radStatesExit (templateWork.stateMachine);

        radProcessExit ();
        radSystemExit (TEMPLATE_SYSTEM_ID);

        exit (1);
    }
    if (radStatesAddHandler (templateWork.stateMachine, TEMPLATE_STATE_ERROR,
                             templateErrorState)
            == ERROR)
    {
        radMsgLog(PRI_HIGH, "radStatesAddHandler failed");
        radStatesExit (templateWork.stateMachine);

        radProcessExit ();
        radSystemExit (TEMPLATE_SYSTEM_ID);

        exit (1);
    }

    radStatesSetState (templateWork.stateMachine, TEMPLATE_STATE_IDLE);


    // create a couple of timers
    templateWork.timerNum1 = radTimerCreate (NULL, timer1Handler, NULL);
    if (templateWork.timerNum1 == NULL)
    {
        radMsgLog(PRI_HIGH, "radTimerCreate failed");
        radStatesExit (templateWork.stateMachine);

        radProcessExit ();
        radSystemExit (TEMPLATE_SYSTEM_ID);

        exit (1);
    }

    templateWork.timerNum2 = radTimerCreate (NULL, timer2Handler, NULL);
    if (templateWork.timerNum2 == NULL)
    {
        radMsgLog(PRI_HIGH, "radTimerCreate failed");
        radTimerDelete (templateWork.timerNum1);
        radStatesExit (templateWork.stateMachine);

        radProcessExit ();
        radSystemExit (TEMPLATE_SYSTEM_ID);

        exit (1);
    }

    // initialize the radlib message router interface
    if (radMsgRouterInit (".") == ERROR)
    {
        radMsgLog(PRI_HIGH, "radMsgRouterInit failed");
        radTimerDelete (templateWork.timerNum2);
        radTimerDelete (templateWork.timerNum1);
        radStatesExit (templateWork.stateMachine);

        radProcessExit ();
        radSystemExit (TEMPLATE_SYSTEM_ID);

        exit (1);
    }

    radMsgRouterMessageRegister (TEMPLATE_MSGID_USER_RESPONSE);


    printf ("\n**************************************************************************************\n");
    printf ("There are now 3 radlib processes running:\n");
    printf ("    radmrouted    the radlib message router daemon\n");
    printf ("    template2d    the template daemon which does the prime number computations\n");
    printf ("    templated     the non-daemon process which does console I/O (and prints this text)\n\n");    
    printf ("Enter a positive integer 'x' then <CR> - the number of prime numbers < 'x'\n");
    printf ("will be returned (it is computed by the 'template2d' daemon)\n\n");
    printf ("There are two timers running which will expire and log a message every\n");
    printf ("%d and %d seconds respectively\n\n", 
            TEMPLATE_TIMER1_PERIOD/1000, TEMPLATE_TIMER2_PERIOD/1000);
    printf ("<CTRL-C> to exit ('templated'), then 'runtemplates stop' to stop the \n");
    printf ("'template2d' and 'radmrouted' (message router) daemons\n");
    printf ("**************************************************************************************\n\n");


    // dummy up a stimulus to get the state machine running
    stim.type = STIM_DUMMY;
    radStatesProcess (templateWork.stateMachine, &stim);


    while (!templateWork.exiting)
    {
        // wait on timers, events, file descriptors, msgs, everything!
        if (radProcessWait (0) == ERROR)
        {
            templateWork.exiting = TRUE;
        }
    }


    radMsgLog(PRI_STATUS, "exiting normally...");

    radTimerDelete (templateWork.timerNum2);
    radTimerDelete (templateWork.timerNum1);
    radStatesExit (templateWork.stateMachine);
    templateSysExit ();

    radProcessExit ();
    radSystemExit (TEMPLATE_SYSTEM_ID);

    exit (0);
}