source: trunk/tools/CmdQd/CmdQd.c@ 7594

Last change on this file since 7594 was 7594, checked in by bird, 24 years ago

Removed some heap debug stuff. fileNormalize is bogus.

File size: 83.7 KB
Line 
1/* $Id: CmdQd.c,v 1.12 2001-12-09 16:11:13 bird Exp $
2 *
3 * Command Queue Daemon / Client.
4 *
5 * Designed to execute commands asyncronus using multiple workers,
6 * and when all commands are submitted wait for them to complete.
7 *
8 * Copyright (c) 2001 knut st. osmundsen (kosmunds@csc.com)
9 *
10 * GPL
11 *
12 */
13
14
15/** @design Command Queue Daemon.
16 *
17 * This command daemon orginated as tool to exploit SMP and UNI systems better
18 * when building large programs, but also when building one specific component of
19 * that program. It is gonna work just like the gnu make -j option.
20 *
21 * @subsection Work flow
22 *
23 * 1. Init daemon process. Creates a daemon process with a given number of
24 * workers. This is a detached process.
25 * 2. Submit jobs to the daemon. The daemon will queue the jobs and the
26 * workers will start working at once there is a job for them.
27 * 3. The nmake script will issue a wait command. We will now wait for all
28 * jobs to finish and in the mean time we'll display output from the jobs.
29 * Failing jobs will be queued up and show when all jobs are finished.
30 * 4. Two options: kill the daemon or start at step 2 again.
31 *
32 *
33 * @subsection Client <-> Daemon communication
34 *
35 * Client and daemon is one and the same executable. This has some advantages
36 * like implicit preloading of the client, fewer source files and fewer programs
37 * to install.
38 *
39 * The communication between the client and the daemon will use shared memory
40 * with an mutex semaphore and two event sems to direct the conversation. The
41 * shared memory block is allocated by the daemon and will have a quite simple
42 * layout:
43 * Mutex Semaphore.
44 * Message Type.
45 * Message specific data:
46 * - Submit job:
47 * Returcode ignore. (4 bytes)
48 * Command to execute. (1 Kb)
49 * Current directory. (260 bytes)
50 * Environment block. (about 62KB)
51 * - Submit job response:
52 * Success/failure indicator.
53 *
54 * - Wait:
55 * Nothing.
56 * - Wait response:
57 * More output indicator.
58 * Success/failure indicator.
59 * Job output (about 63KB)
60 *
61 * - Show jobs:
62 * Nothing.
63 * - Show jobs reponse:
64 * More output indicator.
65 * Job listing (about 63KB)
66 *
67 * - Show failed jobs:
68 * Nothing.
69 * - Show failed jobs reponse:
70 * More output indicator.
71 * Job listing (about 63KB)
72 *
73 * - Show (successfully) completed jobs:
74 * Nothing.
75 * - Show completed jobs reponse:
76 * More output indicator.
77 * Job listing (about 63KB)
78 *
79 * - Show running jobs:
80 * Nothing.
81 * - Show running jobs reponse:
82 * More output indicator.
83 * Job listing (about 63KB)
84 *
85 * - Kill:
86 * Nothing.
87 * - Kill response:
88 * Success/failure indicator.
89 *
90 * - Dies:
91 * Nothing. This is a message to the client saying that the
92 * daemon is dying or allready dead.
93 *
94 * The shared memory block is 64KB.
95 *
96 *
97 * @subsection The Workers
98 *
99 * The workers is individual threads which waits for a job to be submitted to
100 * execution. If the job only contains a single executable program to execute
101 * (no & or &&) it will be executed using DosExecPgm. If it's a multi program
102 * or command job it will be executed by CMD.EXE.
103 *
104 * Output will be read using unamed pipe and buffered. When the job is
105 * completed we'll put the output into either the success queue or the failure
106 * queue depending on the result.
107 *
108 * Note. Process startup needs to be serialized in order to be able to redirect
109 * stdout. We're using a mutex for this.
110 *
111 */
112
113
114/*******************************************************************************
115* Header Files *
116*******************************************************************************/
117#include <stdio.h>
118#include <string.h>
119#include <stdlib.h>
120#include <stdarg.h>
121#include <assert.h>
122#include <direct.h>
123#include <signal.h>
124#include <process.h>
125
126#define INCL_BASE
127#include <os2.h>
128
129
130/*
131 * Memory debugging.
132 */
133#ifdef DEBUGMEMORY
134void my_free(void *);
135void *my_malloc(size_t);
136
137#undef free
138#undef malloc
139
140#define free(pv) my_free(pv)
141#define malloc(cb) my_malloc(cb)
142
143#endif
144
145/*******************************************************************************
146* Defined Constants And Macros *
147*******************************************************************************/
148#define SHARED_MEM_NAME "\\SHAREMEM\\CmdQd"
149#define SHARED_MEM_SIZE 65536
150#define IDLE_TIMEOUT_MS -1 //(60*1000*3)
151#define OUTPUT_CHUNK (8192-8)
152
153#define HF_STDIN 0
154#define HF_STDOUT 1
155#define HF_STDERR 2
156
157/*******************************************************************************
158* Structures and Typedefs *
159*******************************************************************************/
160typedef struct SharedMem
161{
162 HEV hevClient; /* Client will wait on this. */
163 HEV hevDaemon; /* Daemon will wait on this. */
164 HMTX hmtx; /* Owner of the shared memory. */
165 HMTX hmtxClient; /* Take and release this for each */
166 /* client -> server -> client talk. */
167 enum
168 {
169 msgUnknown = 0,
170 msgSubmit = 1,
171 msgSubmitResponse = 2,
172 msgWait = 3,
173 msgWaitResponse = 4,
174 msgKill = 5,
175 msgKillResponse = 6,
176 msgShowJobs = 7,
177 msgShowJobsResponse = 8,
178 msgShowRunningJobs = 9,
179 msgShowRunningJobsResponse = 10,
180 msgShowCompletedJobs = 11,
181 msgShowCompletedJobsResponse = 12,
182 msgShowFailedJobs = 13,
183 msgShowFailedJobsResponse = 14,
184 msgSharedMemOwnerDied = 0xfd,
185 msgClientOwnerDied = 0xfe,
186 msgDying = 0xff
187 } enmMsgType;
188
189 union
190 {
191 struct Submit
192 {
193 unsigned rcIgnore; /* max return code to accept as good. */
194 char szCommand[1024]; /* job command. */
195 char szCurrentDir[CCHMAXPATH]; /* current directory. */
196 int cchEnv; /* Size of the environment block */
197 char szzEnv[SHARED_MEM_SIZE - CCHMAXPATH - 1024 - 4 - 4 - 4 - 4 - 4 - 4];
198 /* Environment block. */
199 } Submit;
200 struct SubmitResponse
201 {
202 BOOL fRc; /* Success idicator. */
203 } SubmitResponse;
204
205
206 struct Wait
207 {
208 int iNothing; /* Dummy. */
209 } Wait;
210 struct WaitResponse
211 {
212 BOOL fMore; /* More data. */
213 int rc; /* return code of first failing job. */
214 /* only valid if fMore == FALSE. */
215 char szOutput[SHARED_MEM_SIZE- 4 - 4 - 4 - 4 - 4 - 4 - 4];
216 /* The output of one or more jobs. */
217 } WaitResponse;
218
219
220 struct Kill
221 {
222 int iNothing; /* dummy. */
223 } Kill;
224 struct KillResponse
225 {
226 BOOL fRc; /* Success idicator. */
227 } KillResponse;
228
229
230 struct ShowJobs
231 {
232 int iNothing; /* Dummy. */
233 } ShowJobs;
234 struct ShowJobsResponse
235 {
236 BOOL fMore; /* More data. */
237 char szOutput[SHARED_MEM_SIZE- 4 - 4 - 4 - 4 - 4 - 4];
238 /* The listing of jobs. */
239 } ShowJobsResponse;
240
241
242 struct ShowRunningJobs
243 {
244 int iNothing; /* Dummy. */
245 } ShowRunningJobs;
246 struct ShowRunningJobsResponse
247 {
248 BOOL fMore; /* More data. */
249 char szOutput[SHARED_MEM_SIZE- 4 - 4 - 4 - 4 - 4 - 4];
250 /* The listing of jobs. */
251 } ShowRunningJobsResponse;
252
253
254 struct ShowCompletedJobs
255 {
256 int iNothing; /* Dummy. */
257 } ShowCompletedJobs;
258 struct ShowCompletedJobsResponse
259 {
260 BOOL fMore; /* More data. */
261 char szOutput[SHARED_MEM_SIZE- 4 - 4 - 4 - 4 - 4 - 4];
262 /* The listing of jobs. */
263 } ShowCompletedJobsResponse;
264
265
266 struct ShowFailedJobs
267 {
268 int iNothing; /* Dummy. */
269 } ShowFailedJobs;
270 struct ShowFailedJobsResponse
271 {
272 BOOL fMore; /* More data. */
273 char szOutput[SHARED_MEM_SIZE- 4 - 4 - 4 - 4 - 4 - 4];
274 /* The listing of jobs. */
275 } ShowFailedJobsResponse;
276
277 } u1;
278
279} SHAREDMEM, *PSHAREDMEM;
280
281
282typedef struct JobOutput
283{
284 struct JobOutput * pNext; /* Pointer to next output chunk. */
285 int cchOutput; /* Bytes used of the szOutput member. */
286 char szOutput[OUTPUT_CHUNK]; /* Output. */
287} JOBOUTPUT, *PJOBOUTPUT;
288
289
290typedef struct Job
291{
292 struct Job * pNext; /* Pointer to next job. */
293 int iJobId; /* JobId. */
294 int rc; /* Result. */
295 PJOBOUTPUT pJobOutput; /* Output. */
296 struct Submit JobInfo; /* Job. */
297} JOB, *PJOB;
298
299
300typedef struct PathCache
301{
302 char szPath[4096 - CCHMAXPATH * 3]; /* The path which this is valid for. */
303 char szCurDir[CCHMAXPATH]; /* The current dir this is valid for. */
304 char szProgram[CCHMAXPATH]; /* The program. */
305 char szResult[CCHMAXPATH]; /* The result. */
306} PATHCACHE, *PPATHCACHE;
307
308
309/*******************************************************************************
310* Global Variables *
311*******************************************************************************/
312PSHAREDMEM pShrMem; /* Pointer to the shared memory. */
313
314HMTX hmtxJobQueue; /* Read/Write mutex for the two jobs queues below. */
315HEV hevJobQueue; /* Incomming job event sem. */
316PJOB pJobQueue; /* Linked list of jobs. */
317PJOB pJobQueueEnd; /* Last job entry. */
318ULONG cJobs; /* Count of jobs submitted. */
319PJOB pJobRunning; /* Linked list of jobs. */
320PJOB pJobRunningEnd; /* Last job entry. */
321
322HMTX hmtxJobQueueFine; /* Read/Write mutex for the next two queues. */
323HEV hevJobQueueFine; /* Posted when there is more output. */
324PJOB pJobCompleted; /* Linked list of successful jobs. */
325PJOB pJobCompletedLast; /* Last successful job entry. */
326PJOB pJobFailed; /* Linked list of failed jobs. */
327PJOB pJobFailedLast; /* Last failed job entry. */
328ULONG cJobsFinished; /* Count of jobs finished (failed or completed). */
329
330HMTX hmtxExec; /* Execute childs mutex sem. Required */
331 /* since we redirect standard files handles */
332 /* and changes the currentdirectory. */
333
334PSZ pszSharedMem = SHARED_MEM_NAME; /* Default shared memname */
335 /* Could be overridden by env.var. CMDQD_MEM_NAME. */
336
337/*******************************************************************************
338* Internal Functions *
339*******************************************************************************/
340void syntax(void);
341
342/* operations */
343int Init(const char *arg0, int cWorkers);
344int Daemon(int cWorkers);
345int DaemonInit(int cWorkers);
346void signalhandlerDaemon(int sig);
347void signalhandlerClient(int sig);
348void Worker(void * iWorkerId);
349char*WorkerArguments(char *pszArg, const char *pszzEnv, const char *pszCommand, char *pszCurDir, PPATHCACHE pPathCache);
350char*fileNormalize(char *pszFilename, char *pszCurDir);
351APIRET fileExist(const char *pszFilename);
352int Submit(int rcIgnore);
353int Wait(void);
354int QueryRunning(void);
355int Kill(void);
356int ShowJobs(void);
357int ShowRunningJobs(void);
358int ShowCompletedJobs(void);
359int ShowFailedJobs(void);
360/* shared memory helpers */
361int shrmemCreate(void);
362int shrmemOpen(void);
363void shrmemFree(void);
364int shrmemSendDaemon(BOOL fWait);
365int shrmemSendClient(int enmMsgTypeResponse);
366
367/* error handling */
368void _Optlink Error(const char *pszFormat, ...);
369
370
371int main(int argc, char **argv)
372{
373 char * psz;
374 char szShrMemName[CCHMAXPATH];
375
376 /*
377 * Display help.
378 */
379 if (argc < 2 || (argv[1][0] == '-'))
380 {
381 syntax();
382 if (argc < 2)
383 {
384 printf("\n!syntax error!");
385 return -1;
386 }
387 return 0;
388 }
389
390 /*
391 * Check for environment variable which gives us
392 * the alternate shared mem name.
393 */
394 if ((psz = getenv("CMDQD_MEM_NAME")) != NULL)
395 {
396 if (strlen(psz) >= CCHMAXPATH - sizeof("\\SHAREMEM\\"))
397 {
398 printf("fatal error: CMDQD_MEM_NAME is is too long.\n");
399 return -1;
400 }
401 strcpy(pszSharedMem = &szShrMemName[0], "\\SHAREMEM\\");
402 strcat(pszSharedMem, psz);
403 }
404
405 /*
406 * String switch on command.
407 */
408 if (!stricmp(argv[1], "submit"))
409 {
410 int rcIgnore = 0;
411 if (argc == 2)
412 {
413 printf("fatal error: There is no job to submit...\n");
414 return -1;
415 }
416 if (argv[2][0] == '-' && (rcIgnore = atoi(argv[2]+1)) <= 0)
417 {
418 printf("syntax error: Invalid ignore return code number...\n");
419 return -1;
420 }
421 return Submit(rcIgnore);
422 }
423 else if (!stricmp(argv[1], "wait"))
424 {
425 return Wait();
426 }
427 else if (!strcmp(argv[1], "queryrunning"))
428 {
429 return QueryRunning();
430 }
431 else if (!strcmp(argv[1], "kill"))
432 {
433 return Kill();
434 }
435 else if (!strcmp(argv[1], "showjobs"))
436 {
437 return ShowJobs();
438 }
439 else if (!strcmp(argv[1], "showrunningjobs"))
440 {
441 return ShowRunningJobs();
442 }
443 else if (!strcmp(argv[1], "showcompletedjobs"))
444 {
445 return ShowCompletedJobs();
446 }
447 else if (!strcmp(argv[1], "showfailedjobs"))
448 {
449 return ShowFailedJobs();
450 }
451 else if (!strcmp(argv[1], "init"))
452 {
453 if (argc != 3 || atoi(argv[2]) <= 0 || atoi(argv[2]) >= 256)
454 {
455 printf("fatal error: invalid/missing number of workers.\n");
456 return -1;
457 }
458 return Init(argv[0], atoi(argv[2]));
459 }
460 else if (!strcmp(argv[1], "!Daemon!"))
461 {
462 if (argc != 3 || atoi(argv[2]) <= 0)
463 {
464 printf("fatal error: no worker count specified or to many parameters.\n");
465 return -2;
466 }
467
468 return Daemon(atoi(argv[2]));
469 }
470 else
471 {
472 syntax();
473 printf("\n!invalid command '%s'.\n", argv[1]);
474 return -1;
475 }
476
477 //return 0;
478}
479
480
481/**
482 * Display syntax.
483 */
484void syntax(void)
485{
486 printf(
487 "Command Queue Daemon v0.0.2\n"
488 "---------------------------\n"
489 "syntax: CmdQd.exe <command> [args]\n"
490 "\n"
491 "commands:\n"
492 " init <workers>\n"
493 " Initiates the command queue daemon with the given number of workers.\n"
494 "\n"
495 " submit [-<n>] <command> [args]\n"
496 " Submits a command to the daemon.\n"
497 " Use '-<n>' to tell use to ignore return code 0-n.\n"
498 "\n"
499 " wait\n"
500 " Wait for all commands which are queued up to complete.\n"
501 " rc = count of failing commands.\n"
502 "\n"
503 " kill\n"
504 " Kills the daemon. Daemon will automatically die after\n"
505 " idling for some time.\n"
506 "\n"
507 " queryrunning\n"
508 " Checks if the daemon is running.\n"
509 " rc = 0 if running; rc != 0 if not running.\n"
510 "\n"
511 " showjobs - shows jobs queued for execution.\n"
512 " showrunningjobs - shows jobs currently running.\n"
513 " showcompletedjobs - shows jobs succesfully executed.\n"
514 " showfailedjobs - shows jobs which failed.\n"
515 "\n"
516 " To use multiple daemons for different purposed assing different\n"
517 " values to CMDQD_MEM_NAME (env.var.) for the sessions.\n"
518 "\n"
519 "Copyright (c) 2001 knut st. osmundsen (kosmunds@csc.com)\n"
520 );
521}
522
523
524/**
525 * Starts a daemon process.
526 * @returns 0 on success.
527 * -4 on error.
528 * @param arg0 Executable filename.
529 * @param cWorkers Number of workers to start.
530 */
531int Init(const char *arg0, int cWorkers)
532{
533 int rc;
534 RESULTCODES Res; /* dummy, unused */
535 char szArg[CCHMAXPATH + 32];
536
537 sprintf(&szArg[0], "%s\t!Daemon! %d", arg0, cWorkers);
538 szArg[strlen(arg0)] = '\0';
539 rc = DosExecPgm(NULL, 0, EXEC_BACKGROUND, &szArg[0], NULL, &Res, &szArg[0]);
540 if (rc)
541 Error("Fatal error: Failed to start daemon. rc=%d\n", rc);
542 return rc;
543}
544
545
546/**
547 * This process is to be a daemon with a given number of works.
548 * @returns 0 on success.
549 * -4 on error.
550 * @param cWorkers Number of workers to start.
551 * @sketch
552 */
553int Daemon(int cWorkers)
554{
555 int rc;
556
557 /*
558 * Init Shared memory
559 */
560 rc = shrmemCreate();
561 if (rc)
562 return rc;
563
564 /*
565 * Init queues and semaphores.
566 */
567 rc = DaemonInit(cWorkers);
568 if (rc)
569 {
570 shrmemFree();
571 return rc;
572 }
573
574 /*
575 * Do work!
576 */
577 rc = shrmemSendDaemon(TRUE);
578 while (!rc)
579 {
580 switch (pShrMem->enmMsgType)
581 {
582 case msgSubmit:
583 {
584 PJOB pJob;
585
586 /*
587 * Make job entry.
588 */
589 pJob = malloc((int)&((PJOB)0)->JobInfo.szzEnv[pShrMem->u1.Submit.cchEnv]);
590 if (pJob)
591 {
592 memcpy(&pJob->JobInfo, &pShrMem->u1.Submit,
593 (int)&((struct Submit *)0)->szzEnv[pShrMem->u1.Submit.cchEnv]);
594 pJob->rc = -1;
595 pJob->pNext = NULL;
596 pJob->pJobOutput = NULL;
597
598 /*
599 * Insert the entry.
600 */
601 rc = DosRequestMutexSem(hmtxJobQueue, SEM_INDEFINITE_WAIT);
602 if (rc)
603 break;
604 if (!pJobQueue)
605 pJobQueueEnd = pJobQueue = pJob;
606 else
607 {
608 pJobQueueEnd->pNext = pJob;
609 pJobQueueEnd = pJob;
610 }
611 pJob->iJobId = cJobs++;
612 DosReleaseMutexSem(hmtxJobQueue);
613
614 /*
615 * Post the queue to wake up workers.
616 */
617 DosPostEventSem(hevJobQueue);
618 pShrMem->u1.SubmitResponse.fRc = TRUE;
619 }
620 else
621 {
622 Error("Internal Error: Out of memory (line=%d)\n", __LINE__);
623 pShrMem->u1.SubmitResponse.fRc = FALSE;
624 }
625 pShrMem->enmMsgType = msgSubmitResponse;
626 rc = shrmemSendDaemon(TRUE);
627 break;
628 }
629
630
631 case msgWait:
632 {
633 PJOB pJob = NULL;
634 PJOBOUTPUT pJobOutput = NULL;
635 char * psz;
636 int cch = 0;
637 char * pszOutput;
638 int cchOutput;
639 int rcFailure = 0;
640 BOOL fMore = TRUE;
641 ULONG ulIgnore;
642 void * pv;
643
644 DosPostEventSem(hevJobQueueFine); /* just so we don't get stuck in the loop... */
645 do
646 {
647 /* init response message */
648 pShrMem->enmMsgType = msgWaitResponse;
649 pShrMem->u1.WaitResponse.szOutput[0] = '\0';
650 pszOutput = &pShrMem->u1.WaitResponse.szOutput[0];
651 cchOutput = sizeof(pShrMem->u1.WaitResponse.szOutput) - 1;
652
653 /*
654 * Wait for output.
655 */
656 /*rc = DosWaitEventSem(hevJobQueueFine, SEM_INDEFINITE_WAIT); - there is some timing problem here, */
657 rc = DosWaitEventSem(hevJobQueueFine, 1000); /* timeout after 1 second. */
658 if (rc && rc != ERROR_TIMEOUT)
659 break;
660 rc = NO_ERROR; /* in case of TIMEOUT */
661
662 /*
663 * Copy output - Optimized so we don't cause to many context switches.
664 */
665 do
666 {
667 /*
668 * Next job.
669 */
670 if (!pJobOutput)
671 {
672 rc = DosRequestMutexSem(hmtxJobQueueFine, SEM_INDEFINITE_WAIT);
673 if (rc)
674 break;
675 pv = pJob;
676 pJob = pJobCompleted;
677 if (pJob)
678 {
679 pJobCompleted = pJob->pNext;
680 if (!pJobCompleted)
681 pJobCompletedLast = NULL;
682 }
683
684 if (!pJob && cJobs == cJobsFinished)
685 { /* all jobs finished, we may start output failures. */
686 pJob = pJobFailed;
687 if (pJob)
688 {
689 if (rcFailure == 0)
690 rcFailure = pJob->rc;
691
692 pJobFailed = pJob->pNext;
693 if (!pJobFailed)
694 pJobFailedLast = NULL;
695 }
696 else
697 fMore = FALSE;
698 }
699 else
700 DosResetEventSem(hevJobQueueFine, &ulIgnore); /* No more output, prepare wait. */
701 DosReleaseMutexSem(hmtxJobQueueFine);
702
703 if (pJob && pJob->pJobOutput)
704 {
705 pJobOutput = pJob->pJobOutput;
706 psz = pJobOutput->szOutput;
707 cch = pJobOutput->cchOutput;
708 }
709 if (pv)
710 free(pv);
711 }
712
713 /*
714 * Anything to output?
715 */
716 if (pJobOutput)
717 {
718 /*
719 * Copy output.
720 */
721 do
722 {
723 if (cch)
724 { /* copy */
725 int cchCopy = min(cch, cchOutput);
726 memcpy(pszOutput, psz, cchCopy);
727 psz += cchCopy; cch -= cchCopy;
728 pszOutput += cchCopy; cchOutput -= cchCopy;
729 }
730 if (!cch)
731 { /* next chunk */
732 pv = pJobOutput;
733 pJobOutput = pJobOutput->pNext;
734 if (pJobOutput)
735 {
736 psz = &pJobOutput->szOutput[0];
737 cch = pJobOutput->cchOutput;
738 }
739 free(pv);
740 }
741 } while (cch && cchOutput);
742 }
743 else
744 break; /* no more output, let's send what we got. */
745
746 } while (!rc && fMore && cchOutput);
747
748 /*
749 * We've got a message to send.
750 */
751 if (rc)
752 break;
753 *pszOutput = '\0';
754 pShrMem->u1.WaitResponse.rc = rcFailure;
755 pShrMem->u1.WaitResponse.fMore = fMore;
756 rc = shrmemSendDaemon(TRUE);
757 } while (!rc && fMore);
758
759 /*
760 * Check if the wait client died.
761 */
762 if (rc == ERROR_ALREADY_POSTED) /* seems like this is the rc we get. */
763 {
764 /*
765 * BUGBUG: This code is really fishy, but I'm to tired to make a real fix now.
766 * Hopefully this solves my current problem.
767 */
768 ULONG ulDummy;
769 rc = DosRequestMutexSem(pShrMem->hmtx, 500);
770 rc = DosResetEventSem(pShrMem->hevClient, &ulDummy);
771 pShrMem->enmMsgType = msgUnknown;
772 rc = shrmemSendDaemon(TRUE);
773 }
774 break;
775 }
776
777
778 case msgKill:
779 {
780 pShrMem->enmMsgType = msgKillResponse;
781 pShrMem->u1.KillResponse.fRc = TRUE;
782 shrmemSendDaemon(FALSE);
783 rc = -1;
784 break;
785 }
786
787
788 case msgShowJobs:
789 {
790 /*
791 * Gain access to the job list.
792 */
793 rc = DosRequestMutexSem(hmtxJobQueue, SEM_INDEFINITE_WAIT);
794 if (!rc)
795 {
796 int iJob = 0;
797 PJOB pJob = pJobQueue;
798
799 /*
800 * Big loop making and sending all messages.
801 */
802 do
803 {
804 int cch;
805 char * pszOutput;
806 int cchOutput;
807
808 /*
809 * Make one message.
810 */
811 pShrMem->enmMsgType = msgShowJobsResponse;
812 pszOutput = &pShrMem->u1.ShowJobsResponse.szOutput[0];
813 cchOutput = sizeof(pShrMem->u1.ShowJobsResponse.szOutput) - 1;
814
815 /*
816 * Insert job info.
817 */
818 while (pJob)
819 {
820 char szTmp[8192]; /* this is sufficient for one job. */
821
822 /*
823 * Format output in temporary buffer and check if
824 * it's space left in the share buffer.
825 */
826 cch = sprintf(szTmp,
827 "------------------ JobId %d - %d\n"
828 " command: %s\n"
829 " curdir: %s\n"
830 " rcIgnore: %d\n",
831 pJob->iJobId,
832 iJob,
833 pJob->JobInfo.szCommand,
834 pJob->JobInfo.szCurrentDir,
835 pJob->JobInfo.rcIgnore);
836 if (cch > cchOutput)
837 break;
838
839 /*
840 * Copy from temporary to shared buffer.
841 */
842 memcpy(pszOutput, szTmp, cch);
843 pszOutput += cch;
844 cchOutput -= cch;
845
846 /*
847 * Next job.
848 */
849 pJob = pJob->pNext;
850 iJob++;
851 }
852
853 /*
854 * Send the message.
855 */
856 *pszOutput = '\0';
857 pShrMem->u1.ShowJobsResponse.fMore = pJob != NULL;
858 if (!pJob)
859 DosReleaseMutexSem(hmtxJobQueue);
860 rc = shrmemSendDaemon(TRUE);
861
862 } while (!rc && pJob);
863
864
865 /*
866 * Release the job list.
867 */
868 DosReleaseMutexSem(hmtxJobQueue);
869 }
870 else
871 {
872 /* init response message */
873 pShrMem->enmMsgType = msgShowJobsResponse;
874 sprintf(&pShrMem->u1.ShowJobsResponse.szOutput[0],
875 "Internal Error. Requesting of hmtxJobQueue failed with rc=%d\n",
876 rc);
877 rc = shrmemSendDaemon(TRUE);
878 }
879
880
881 /*
882 * Check if the waiting client died.
883 */
884 if (rc == ERROR_ALREADY_POSTED) /* seems like this is the rc we get. */
885 {
886 /*
887 * BUGBUG: This code is really fishy, but I'm to tired to make a real fix now.
888 * Hopefully this solves my current problem.
889 */
890 ULONG ulDummy;
891 rc = DosRequestMutexSem(pShrMem->hmtx, 500);
892 rc = DosResetEventSem(pShrMem->hevClient, &ulDummy);
893 pShrMem->enmMsgType = msgUnknown;
894 rc = shrmemSendDaemon(TRUE);
895 }
896 break;
897 }
898
899
900 case msgShowFailedJobs:
901 {
902 /*
903 * Gain access to the finished job list.
904 */
905 rc = DosRequestMutexSem(hmtxJobQueueFine, SEM_INDEFINITE_WAIT);
906 if (!rc)
907 {
908 int iJob = 0;
909 PJOB pJob = pJobFailed;
910
911 /*
912 * Big loop making and sending all messages.
913 */
914 do
915 {
916 int cch;
917 char * pszOutput;
918 int cchOutput;
919
920 /*
921 * Make one message.
922 */
923 pShrMem->enmMsgType = msgShowFailedJobsResponse;
924 pszOutput = &pShrMem->u1.ShowFailedJobsResponse.szOutput[0];
925 cchOutput = sizeof(pShrMem->u1.ShowFailedJobsResponse.szOutput) - 1;
926
927 /*
928 * Insert job info.
929 */
930 while (pJob)
931 {
932 char szTmp[8192]; /* this is sufficient for one job. */
933
934 /*
935 * Format output in temporary buffer and check if
936 * it's space left in the share buffer.
937 */
938 cch = sprintf(szTmp,
939 "------------------ Failed JobId %d - %d\n"
940 " command: %s\n"
941 " curdir: %s\n"
942 " rc: %d (rcIgnore=%d)\n",
943 pJob->iJobId,
944 iJob,
945 pJob->JobInfo.szCommand,
946 pJob->JobInfo.szCurrentDir,
947 pJob->rc,
948 pJob->JobInfo.rcIgnore);
949 if (cch > cchOutput)
950 break;
951
952 /*
953 * Copy from temporary to shared buffer.
954 */
955 memcpy(pszOutput, szTmp, cch);
956 pszOutput += cch;
957 cchOutput -= cch;
958
959 /*
960 * Next job.
961 */
962 pJob = pJob->pNext;
963 iJob++;
964 }
965
966 /*
967 * Send the message.
968 */
969 *pszOutput = '\0';
970 pShrMem->u1.ShowFailedJobsResponse.fMore = pJob != NULL;
971 if (!pJob)
972 DosReleaseMutexSem(hmtxJobQueueFine);
973 rc = shrmemSendDaemon(TRUE);
974
975 } while (!rc && pJob);
976
977
978 /*
979 * Release the job list.
980 */
981 DosReleaseMutexSem(hmtxJobQueueFine);
982 }
983 else
984 {
985 /* init response message */
986 pShrMem->enmMsgType = msgShowFailedJobsResponse;
987 sprintf(&pShrMem->u1.ShowFailedJobsResponse.szOutput[0],
988 "Internal Error. Requesting of hmtxJobQueue failed with rc=%d\n",
989 rc);
990 rc = shrmemSendDaemon(TRUE);
991 }
992
993
994 /*
995 * Check if the waiting client died.
996 */
997 if (rc == ERROR_ALREADY_POSTED) /* seems like this is the rc we get. */
998 {
999 /*
1000 * BUGBUG: This code is really fishy, but I'm to tired to make a real fix now.
1001 * Hopefully this solves my current problem.
1002 */
1003 ULONG ulDummy;
1004 rc = DosRequestMutexSem(pShrMem->hmtx, 500);
1005 rc = DosResetEventSem(pShrMem->hevClient, &ulDummy);
1006 pShrMem->enmMsgType = msgUnknown;
1007 rc = shrmemSendDaemon(TRUE);
1008 }
1009 break;
1010 }
1011
1012
1013 case msgShowRunningJobs:
1014 {
1015 /*
1016 * Gain access to the job list.
1017 */
1018 rc = DosRequestMutexSem(hmtxJobQueue, SEM_INDEFINITE_WAIT);
1019 if (!rc)
1020 {
1021 int iJob = 0;
1022 PJOB pJob = pJobRunning;
1023
1024 /*
1025 * Big loop making and sending all messages.
1026 */
1027 do
1028 {
1029 int cch;
1030 char * pszOutput;
1031 int cchOutput;
1032
1033 /*
1034 * Make one message.
1035 */
1036 pShrMem->enmMsgType = msgShowRunningJobsResponse;
1037 pszOutput = &pShrMem->u1.ShowRunningJobsResponse.szOutput[0];
1038 cchOutput = sizeof(pShrMem->u1.ShowRunningJobsResponse.szOutput) - 1;
1039
1040 /*
1041 * Insert job info.
1042 */
1043 while (pJob)
1044 {
1045 char szTmp[8192]; /* this is sufficient for one job. */
1046
1047 /*
1048 * Format output in temporary buffer and check if
1049 * it's space left in the share buffer.
1050 */
1051 cch = sprintf(szTmp,
1052 "------------------ Running JobId %d - %d\n"
1053 " command: %s\n"
1054 " curdir: %s\n"
1055 " rcIgnore: %d\n",
1056 pJob->iJobId,
1057 iJob,
1058 pJob->JobInfo.szCommand,
1059 pJob->JobInfo.szCurrentDir,
1060 pJob->JobInfo.rcIgnore);
1061 if (cch > cchOutput)
1062 break;
1063
1064 /*
1065 * Copy from temporary to shared buffer.
1066 */
1067 memcpy(pszOutput, szTmp, cch);
1068 pszOutput += cch;
1069 cchOutput -= cch;
1070
1071 /*
1072 * Next job.
1073 */
1074 pJob = pJob->pNext;
1075 iJob++;
1076 }
1077
1078 /*
1079 * Send the message.
1080 */
1081 *pszOutput = '\0';
1082 pShrMem->u1.ShowRunningJobsResponse.fMore = pJob != NULL;
1083 if (!pJob)
1084 DosReleaseMutexSem(hmtxJobQueue);
1085 rc = shrmemSendDaemon(TRUE);
1086
1087 } while (!rc && pJob);
1088
1089
1090 /*
1091 * Release the job list.
1092 */
1093 DosReleaseMutexSem(hmtxJobQueue);
1094 }
1095 else
1096 {
1097 /* init response message */
1098 pShrMem->enmMsgType = msgShowRunningJobsResponse;
1099 sprintf(&pShrMem->u1.ShowRunningJobsResponse.szOutput[0],
1100 "Internal Error. Requesting of hmtxJobQueue failed with rc=%d\n",
1101 rc);
1102 rc = shrmemSendDaemon(TRUE);
1103 }
1104
1105
1106 /*
1107 * Check if the waiting client died.
1108 */
1109 if (rc == ERROR_ALREADY_POSTED) /* seems like this is the rc we get. */
1110 {
1111 /*
1112 * BUGBUG: This code is really fishy, but I'm to tired to make a real fix now.
1113 * Hopefully this solves my current problem.
1114 */
1115 ULONG ulDummy;
1116 rc = DosRequestMutexSem(pShrMem->hmtx, 500);
1117 rc = DosResetEventSem(pShrMem->hevClient, &ulDummy);
1118 pShrMem->enmMsgType = msgUnknown;
1119 rc = shrmemSendDaemon(TRUE);
1120 }
1121 break;
1122 }
1123
1124
1125
1126 case msgShowCompletedJobs:
1127 {
1128 /*
1129 * Gain access to the finished job list.
1130 */
1131 rc = DosRequestMutexSem(hmtxJobQueueFine, SEM_INDEFINITE_WAIT);
1132 if (!rc)
1133 {
1134 int iJob = 0;
1135 PJOB pJob = pJobCompleted;
1136
1137 /*
1138 * Big loop making and sending all messages.
1139 */
1140 do
1141 {
1142 int cch;
1143 char * pszOutput;
1144 int cchOutput;
1145
1146 /*
1147 * Make one message.
1148 */
1149 pShrMem->enmMsgType = msgShowCompletedJobsResponse;
1150 pszOutput = &pShrMem->u1.ShowCompletedJobsResponse.szOutput[0];
1151 cchOutput = sizeof(pShrMem->u1.ShowCompletedJobsResponse.szOutput) - 1;
1152
1153 /*
1154 * Insert job info.
1155 */
1156 while (pJob)
1157 {
1158 char szTmp[8192]; /* this is sufficient for one job. */
1159
1160 /*
1161 * Format output in temporary buffer and check if
1162 * it's space left in the share buffer.
1163 */
1164 cch = sprintf(szTmp,
1165 "------------------ Completed JobId %d - %d\n"
1166 " command: %s\n"
1167 " curdir: %s\n"
1168 " rcIgnore: %d\n",
1169 pJob->iJobId,
1170 iJob,
1171 pJob->JobInfo.szCommand,
1172 pJob->JobInfo.szCurrentDir,
1173 pJob->JobInfo.rcIgnore);
1174 if (cch > cchOutput)
1175 break;
1176
1177 /*
1178 * Copy from temporary to shared buffer.
1179 */
1180 memcpy(pszOutput, szTmp, cch);
1181 pszOutput += cch;
1182 cchOutput -= cch;
1183
1184 /*
1185 * Next job.
1186 */
1187 pJob = pJob->pNext;
1188 iJob++;
1189 }
1190
1191 /*
1192 * Send the message.
1193 */
1194 *pszOutput = '\0';
1195 pShrMem->u1.ShowCompletedJobsResponse.fMore = pJob != NULL;
1196 if (!pJob)
1197 DosReleaseMutexSem(hmtxJobQueueFine);
1198 rc = shrmemSendDaemon(TRUE);
1199
1200 } while (!rc && pJob);
1201
1202
1203 /*
1204 * Release the finished job list.
1205 */
1206 DosReleaseMutexSem(hmtxJobQueueFine);
1207 }
1208 else
1209 {
1210 /* init response message */
1211 pShrMem->enmMsgType = msgShowCompletedJobsResponse;
1212 sprintf(&pShrMem->u1.ShowCompletedJobsResponse.szOutput[0],
1213 "Internal Error. Requesting of hmtxJobQueue failed with rc=%d\n",
1214 rc);
1215 rc = shrmemSendDaemon(TRUE);
1216 }
1217
1218
1219 /*
1220 * Check if the waiting client died.
1221 */
1222 if (rc == ERROR_ALREADY_POSTED) /* seems like this is the rc we get. */
1223 {
1224 /*
1225 * BUGBUG: This code is really fishy, but I'm to tired to make a real fix now.
1226 * Hopefully this solves my current problem.
1227 */
1228 ULONG ulDummy;
1229 rc = DosRequestMutexSem(pShrMem->hmtx, 500);
1230 rc = DosResetEventSem(pShrMem->hevClient, &ulDummy);
1231 pShrMem->enmMsgType = msgUnknown;
1232 rc = shrmemSendDaemon(TRUE);
1233 }
1234 break;
1235 }
1236
1237
1238 case msgClientOwnerDied:
1239 {
1240 DosCloseMutexSem(pShrMem->hmtxClient);
1241 rc = DosCreateMutexSem(NULL, &pShrMem->hmtxClient, DC_SEM_SHARED, FALSE);
1242 if (rc)
1243 Error("Failed to restore dead client semaphore\n");
1244 pShrMem->enmMsgType = msgUnknown;
1245 rc = shrmemSendDaemon(TRUE);
1246 break;
1247 }
1248
1249
1250 case msgSharedMemOwnerDied:
1251 {
1252 DosCloseMutexSem(pShrMem->hmtx);
1253 rc = DosCreateMutexSem(NULL, &pShrMem->hmtx, DC_SEM_SHARED, TRUE);
1254 if (rc)
1255 Error("Failed to restore dead shared mem semaphore\n");
1256 pShrMem->enmMsgType = msgUnknown;
1257 rc = shrmemSendDaemon(TRUE);
1258 break;
1259 }
1260
1261
1262 default:
1263 Error("Internal error: Invalid message id %d\n", pShrMem->enmMsgType, rc);
1264 pShrMem->enmMsgType = msgUnknown;
1265 rc = shrmemSendDaemon(TRUE);
1266 }
1267 }
1268
1269 /*
1270 * Set dying msg type. shrmemFree posts the hevClient so clients
1271 * waiting for the daemon to respond will quit.
1272 */
1273 pShrMem->enmMsgType = msgDying;
1274
1275 /*
1276 * Cleanup.
1277 */
1278 shrmemFree();
1279 DosCloseMutexSem(hmtxJobQueue);
1280 DosCloseMutexSem(hmtxJobQueueFine);
1281 DosCloseEventSem(hevJobQueueFine);
1282 DosCloseMutexSem(hmtxExec);
1283 DosCloseEventSem(hevJobQueue);
1284
1285 return 0;
1286}
1287
1288
1289/**
1290 * Help which does most of the daemon init stuff.
1291 * @returns 0 on success.
1292 * @param cWorkers Number of worker threads to start.
1293 */
1294int DaemonInit(int cWorkers)
1295{
1296 int rc;
1297 int i;
1298
1299 /*
1300 * Init queues and semaphores.
1301 */
1302 rc = DosCreateEventSem(NULL, &hevJobQueue, 0, FALSE);
1303 if (!rc)
1304 {
1305 rc = DosCreateMutexSem(NULL, &hmtxJobQueue, 0, FALSE);
1306 if (!rc)
1307 {
1308 rc = DosCreateMutexSem(NULL, &hmtxJobQueueFine, 0, FALSE);
1309 if (!rc)
1310 {
1311 rc = DosCreateEventSem(NULL, &hevJobQueueFine, 0, FALSE);
1312 if (!rc)
1313 {
1314 rc = DosCreateMutexSem(NULL, &hmtxExec, 0, FALSE);
1315 if (!rc)
1316 {
1317 /*
1318 * Start workers.
1319 */
1320 rc = 0;
1321 for (i = 0; i < cWorkers; i++)
1322 if (_beginthread(Worker, NULL, 64*1024, (void*)i) == -1)
1323 {
1324 Error("Fatal error: failed to create worker thread no. %d\n", i);
1325 rc = -1;
1326 break;
1327 }
1328 if (!rc)
1329 {
1330 DosSetMaxFH(cWorkers * 6 + 20);
1331 return 0; /* success! */
1332 }
1333
1334 /* failure */
1335 DosCloseMutexSem(hmtxExec);
1336 }
1337 else
1338 Error("Fatal error: failed to create exec mutex. rc=%d", rc);
1339 DosCloseEventSem(hevJobQueueFine);
1340 }
1341 else
1342 Error("Fatal error: failed to create job queue fine event sem. rc=%d", rc);
1343 DosCloseMutexSem(hmtxJobQueueFine);
1344 }
1345 else
1346 Error("Fatal error: failed to create job queue fine mutex. rc=%d", rc);
1347 DosCloseMutexSem(hmtxJobQueue);
1348 }
1349 else
1350 Error("Fatal error: failed to create job queue mutex. rc=%d", rc);
1351 DosCloseEventSem(hevJobQueue);
1352 }
1353 else
1354 Error("Fatal error: failed to create job queue event sem. rc=%d", rc);
1355
1356 return rc;
1357}
1358
1359
1360/**
1361 * Daemon signal handler.
1362 */
1363void signalhandlerDaemon(int sig)
1364{
1365 /*
1366 * Set dying msg type. shrmemFree posts the hevClient so clients
1367 * waiting for the daemon to respond will quit.
1368 */
1369 pShrMem->enmMsgType = msgDying;
1370
1371 /*
1372 * Free and exit.
1373 */
1374 shrmemFree();
1375 exit(-42);
1376 sig = sig;
1377}
1378
1379
1380/**
1381 * Client signal handler.
1382 */
1383void signalhandlerClient(int sig)
1384{
1385 shrmemFree();
1386 exit(-42);
1387 sig = sig;
1388}
1389
1390
1391
1392/**
1393 * Worker thread.
1394 * @param iWorkerId The worker process id.
1395 * @sketch
1396 */
1397void Worker(void * iWorkerId)
1398{
1399 PATHCACHE PathCache;
1400 memset(&PathCache, 0, sizeof(PathCache));
1401
1402 while (!DosWaitEventSem(hevJobQueue, SEM_INDEFINITE_WAIT))
1403 {
1404 PJOB pJob;
1405
1406 /*
1407 * Get job.
1408 */
1409 if (DosRequestMutexSem(hmtxJobQueue, SEM_INDEFINITE_WAIT))
1410 return;
1411 pJob = pJobQueue;
1412 if (pJob)
1413 {
1414 /* remove from input queue */
1415 if (pJob != pJobQueueEnd)
1416 pJobQueue = pJob->pNext;
1417 else
1418 {
1419 ULONG ulIgnore;
1420 pJobQueue = pJobQueueEnd = NULL;
1421 DosResetEventSem(hevJobQueue, &ulIgnore);
1422 }
1423
1424 /* insert into running */
1425 pJob->pNext = NULL;
1426 if (pJobRunningEnd)
1427 pJobRunningEnd = pJobRunningEnd->pNext = pJob;
1428 else
1429 pJobRunning = pJobRunningEnd = pJob;
1430 }
1431 DosReleaseMutexSem(hmtxJobQueue);
1432
1433 /*
1434 * Execute job.
1435 */
1436 if (pJob)
1437 {
1438 int rc;
1439 char szArg[4096];
1440 char szObj[256];
1441 PJOBOUTPUT pJobOutput = NULL;
1442 PJOBOUTPUT pJobOutputLast = NULL;
1443 RESULTCODES Res;
1444 PID pid;
1445 HFILE hStdOut = HF_STDOUT;
1446 HFILE hStdErr = HF_STDERR;
1447 HFILE hStdOutSave = -1;
1448 HFILE hStdErrSave = -1;
1449 HPIPE hPipeR = NULLHANDLE;
1450 HPIPE hPipeW = NULLHANDLE;
1451
1452 //printf("debug-%d: start %s\n", iWorkerId, pJob->JobInfo.szCommand);
1453
1454 /*
1455 * Redirect output and start process.
1456 */
1457 WorkerArguments(&szArg[0], &pJob->JobInfo.szzEnv[0], &pJob->JobInfo.szCommand[0],
1458 &pJob->JobInfo.szCurrentDir[0], &PathCache);
1459 rc = DosCreatePipe(&hPipeR, &hPipeW, sizeof(pJobOutput->szOutput) - 1);
1460 if (rc)
1461 {
1462 Error("Internal Error: Failed to create pipe! rc=%d\n", rc);
1463 return;
1464 }
1465
1466 if (DosRequestMutexSem(hmtxExec, SEM_INDEFINITE_WAIT))
1467 {
1468 DosClose(hPipeR);
1469 DosClose(hPipeW);
1470 return;
1471 }
1472
1473 pJob->pJobOutput = pJobOutput = pJobOutputLast = malloc(sizeof(JOBOUTPUT));
1474 pJobOutput->pNext = NULL;
1475 pJobOutput->cchOutput = sprintf(pJobOutput->szOutput, "Job: %s\n", pJob->JobInfo.szCommand);
1476
1477 rc = DosSetDefaultDisk( pJob->JobInfo.szCurrentDir[0] >= 'a'
1478 ? pJob->JobInfo.szCurrentDir[0] - 'a' + 1
1479 : pJob->JobInfo.szCurrentDir[0] - 'A' + 1);
1480 rc += DosSetCurrentDir(pJob->JobInfo.szCurrentDir);
1481 if (!rc)
1482 {
1483 assert( pJob->JobInfo.szzEnv[pJob->JobInfo.cchEnv-1] == '\0'
1484 && pJob->JobInfo.szzEnv[pJob->JobInfo.cchEnv-2] == '\0');
1485 DosDupHandle(HF_STDOUT, &hStdOutSave);
1486 DosDupHandle(HF_STDERR, &hStdErrSave);
1487 DosDupHandle(hPipeW, &hStdOut);
1488 DosDupHandle(hPipeW, &hStdErr);
1489 rc = DosExecPgm(szObj, sizeof(szObj), EXEC_ASYNCRESULT,
1490 szArg, pJob->JobInfo.szzEnv, &Res, szArg);
1491 DosClose(hStdOut); hStdOut = HF_STDOUT;
1492 DosClose(hStdErr); hStdErr = HF_STDERR;
1493 DosDupHandle(hStdOutSave, &hStdOut);
1494 DosDupHandle(hStdErrSave, &hStdErr);
1495 DosClose(hStdOutSave);
1496 DosClose(hStdErrSave);
1497 DosReleaseMutexSem(hmtxExec);
1498 DosClose(hPipeW);
1499
1500
1501 /*
1502 * Read Output.
1503 */
1504 if (!rc)
1505 {
1506 ULONG cchRead;
1507 ULONG cchRead2 = 0;
1508
1509 cchRead = sizeof(pJobOutput->szOutput) - pJobOutput->cchOutput - 1;
1510 while (((rc = DosRead(hPipeR,
1511 &pJobOutput->szOutput[pJobOutput->cchOutput],
1512 cchRead, &cchRead2)) == NO_ERROR
1513 || rc == ERROR_MORE_DATA)
1514 && cchRead2 != 0)
1515 {
1516 pJobOutput->cchOutput += cchRead2;
1517 pJobOutput->szOutput[pJobOutput->cchOutput] = '\0';
1518
1519 /* prepare next read */
1520 cchRead = sizeof(pJobOutput->szOutput) - pJobOutput->cchOutput - 1;
1521 if (cchRead < 16)
1522 {
1523 pJobOutput = pJobOutput->pNext = malloc(sizeof(JOBOUTPUT));
1524 pJobOutput->pNext = NULL;
1525 pJobOutput->cchOutput = 0;
1526 cchRead = sizeof(pJobOutput->szOutput) - 1;
1527 }
1528 cchRead2 = 0;
1529 }
1530 rc = 0;
1531 }
1532
1533 /* finished reading */
1534 DosClose(hPipeR);
1535
1536 /*
1537 * Get result.
1538 */
1539 if (!rc)
1540 {
1541 DosWaitChild(DCWA_PROCESS, DCWW_WAIT, &Res, &pid, Res.codeTerminate);
1542 if ( Res.codeResult <= pJob->JobInfo.rcIgnore
1543 && Res.codeTerminate == TC_EXIT)
1544 pJob->rc = 0;
1545 else
1546 {
1547 pJob->rc = -1;
1548 rc = sprintf(szArg, "failed with rc=%d term=%d\n", Res.codeResult, Res.codeTerminate);
1549 if (rc + pJobOutput->cchOutput + 1 >= sizeof(pJobOutput->szOutput))
1550 {
1551 pJobOutput = pJobOutput->pNext = malloc(sizeof(JOBOUTPUT));
1552 pJobOutput->pNext = NULL;
1553 pJobOutput->cchOutput = 0;
1554 }
1555 strcpy(&pJobOutput->szOutput[pJobOutput->cchOutput], szArg);
1556 pJobOutput->cchOutput += rc;
1557 }
1558 }
1559 else
1560 {
1561 pJobOutput->cchOutput += sprintf(&pJobOutput->szOutput[pJobOutput->cchOutput],
1562 "DosExecPgm failed with rc=%d for command %s %s\n"
1563 " obj=%s\n",
1564 rc, szArg, pJob->JobInfo.szCommand, szObj);
1565 pJob->rc = -1;
1566 }
1567 }
1568 else
1569 {
1570 /*
1571 * ChDir failed.
1572 */
1573 DosReleaseMutexSem(hmtxExec);
1574 pJobOutput->cchOutput += sprintf(&pJobOutput->szOutput[pJobOutput->cchOutput ],
1575 "Failed to set current directory to: %s\n",
1576 pJob->JobInfo.szCurrentDir);
1577 pJob->rc = -1;
1578 DosClose(hPipeR);
1579 }
1580
1581
1582 /*
1583 * Remove from the running queue.
1584 */
1585 if (DosRequestMutexSem(hmtxJobQueue, SEM_INDEFINITE_WAIT))
1586 return;
1587
1588 if (pJobRunning != pJob)
1589 {
1590 PJOB pJobCur = pJobRunning;
1591 while (pJobCur)
1592 {
1593 if (pJobCur->pNext == pJob)
1594 {
1595 pJobCur->pNext = pJob->pNext;
1596 if (pJob == pJobRunningEnd)
1597 pJobRunningEnd = pJobCur;
1598 break;
1599 }
1600 pJobCur = pJobCur->pNext;
1601 }
1602 }
1603 else
1604 pJobRunning = pJobRunningEnd = NULL;
1605
1606 DosReleaseMutexSem(hmtxJobQueue);
1607
1608
1609 /*
1610 * Insert result in result queue.
1611 */
1612 if (DosRequestMutexSem(hmtxJobQueueFine, SEM_INDEFINITE_WAIT))
1613 return;
1614 pJob->pNext = NULL;
1615 if (!pJob->rc) /* 0 on success. */
1616 {
1617 if (pJobCompletedLast)
1618 pJobCompletedLast->pNext = pJob;
1619 else
1620 pJobCompleted = pJob;
1621 pJobCompletedLast = pJob;
1622 }
1623 else
1624 {
1625 if (pJobFailedLast)
1626 pJobFailedLast->pNext = pJob;
1627 else
1628 pJobFailed = pJob;
1629 pJobFailedLast = pJob;
1630 }
1631 cJobsFinished++;
1632 DosReleaseMutexSem(hmtxJobQueueFine);
1633 /* wake up Wait. */
1634 DosPostEventSem(hevJobQueueFine);
1635 //printf("debug-%d: fine\n", iWorkerId);
1636 }
1637 }
1638 iWorkerId = iWorkerId;
1639}
1640
1641
1642/**
1643 * Builds the input to DosExecPgm.
1644 * Will execute programs directly and command thru the shell.
1645 *
1646 * @returns pszArg.
1647 * @param pszArg Arguments to DosExecPgm.(output)
1648 * Assumes that the buffer is large enought.
1649 * @param pszzEnv Pointer to environment block.
1650 * @param pszCommand Command to execute.
1651 * @param pszCurDir From where the command is to executed.
1652 * @param pPathCache Used to cache the last path, executable, and the search result.
1653 */
1654char *WorkerArguments(char *pszArg, const char *pszzEnv, const char *pszCommand, char *pszCurDir, PPATHCACHE pPathCache)
1655{
1656 BOOL fCMD = FALSE;
1657 const char *psz;
1658 const char *psz2;
1659 char * pszW;
1660 char ch;
1661 int cch;
1662 APIRET rc;
1663
1664 /*
1665 * Check if this is multiple command separated by either &, && or |.
1666 * Currently ignoring quotes for this test.
1667 */
1668 if ( strchr(pszCommand, '&')
1669 || strchr(pszCommand, '|'))
1670 {
1671 strcpy(pszArg, "cmd.exe"); /* doesn't use comspec, just defaults to cmd.exe in all cases. */
1672 fCMD = TRUE;
1673 psz2 = pszCommand; /* start of arguments. */
1674 }
1675 else
1676 {
1677 char chEnd = ' ';
1678
1679 /*
1680 * Parse out the first name.
1681 */
1682 for (psz = pszCommand; *psz == '\t' || *psz == ' ';) //strip(,'L');
1683 psz++;
1684 if (*psz == '"' || *psz == '\'')
1685 chEnd = *psz++;
1686 psz2 = psz;
1687 if (chEnd == ' ')
1688 {
1689 while ((ch = *psz) != '\0' && ch != ' ' && ch != '\t')
1690 psz++;
1691 }
1692 else
1693 {
1694 while ((ch = *psz) != '\0' && ch != chEnd)
1695 psz++;
1696 }
1697 *pszArg = '\0';
1698 strncat(pszArg, psz2, psz - psz2);
1699 psz2 = psz+1; /* start of arguments. */
1700 }
1701
1702
1703 /*
1704 * Resolve the executable name if not qualified.
1705 * NB! We doesn't fully support references to other driveletters yet. (TODO/BUGBUG)
1706 */
1707 /* correct slashes */
1708 pszW = pszArg;
1709 while ((pszW = strchr(pszW, '//')) != NULL)
1710 *pszW++ = '\\';
1711
1712 /* make sure it ends with .exe */
1713 pszW = pszArg + strlen(pszArg) - 1;
1714 while (pszW > pszArg && *pszW != '.' && *pszW != '\\')
1715 pszW--;
1716 if (*pszW != '.')
1717 strcat(pszArg, ".exe");
1718
1719 if (pszArg[1] != ':' || *pszArg == *pszCurDir)
1720 {
1721 rc = -1; /* indicate that we've not found the file. */
1722
1723 /* relative path? - expand it */
1724 if (strchr(pszArg, '\\') || pszArg[1] == ':')
1725 { /* relative path - expand it and check for file existence */
1726 fileNormalize(pszArg, pszCurDir);
1727 rc = fileExist(pszArg);
1728 }
1729 else
1730 { /* Search path. */
1731 const char *pszPath = pszzEnv;
1732 while (*pszPath != '\0' && strncmp(pszPath, "PATH=", 5))
1733 pszPath += strlen(pszPath) + 1;
1734
1735 if (pszPath && *pszPath != '\0')
1736 {
1737 /* check cache */
1738 if ( !strcmp(pPathCache->szProgram, pszArg)
1739 && !strcmp(pPathCache->szPath, pszPath)
1740 && !strcmp(pPathCache->szCurDir, pszCurDir)
1741 )
1742 {
1743 strcpy(pszArg, pPathCache->szResult);
1744 rc = fileExist(pszArg);
1745 }
1746
1747 if (rc)
1748 { /* search path */
1749 char szResult[CCHMAXPATH];
1750 rc = DosSearchPath(SEARCH_IGNORENETERRS, (PSZ)pszPath, pszArg, &szResult[0] , sizeof(szResult));
1751 if (!rc)
1752 {
1753 strcpy(pszArg, szResult);
1754
1755 /* update cache */
1756 strcpy(pPathCache->szProgram, pszArg);
1757 strcpy(pPathCache->szPath, pszPath);
1758 strcpy(pPathCache->szCurDir, pszCurDir);
1759 strcpy(pPathCache->szResult, szResult);
1760 }
1761 }
1762 }
1763 }
1764 }
1765 /* else nothing to do - assume full path (btw. we don't have the current dir for other drives anyway :-) */
1766 else
1767 rc = !fCMD ? fileExist(pszArg) : NO_ERROR;
1768
1769 /* In case of error use CMD */
1770 if (rc && !fCMD)
1771 {
1772 strcpy(pszArg, "cmd.exe"); /* doesn't use comspec, just defaults to cmd.exe in all cases. */
1773 fCMD = TRUE;
1774 psz2 = pszCommand; /* start of arguments. */
1775 }
1776
1777
1778 /*
1779 * Complete the argument string.
1780 * ---
1781 * szArg current holds the command.
1782 * psz2 points to the first parameter. (needs strip(,'L'))
1783 */
1784 while ((ch = *psz2) != '\0' && (ch == '\t' || ch == ' '))
1785 psz2++;
1786
1787 pszW = pszArg + strlen(pszArg) + 1;
1788 cch = strlen(psz2);
1789 if (!fCMD)
1790 {
1791 memcpy(pszW, psz2, ++cch);
1792 pszW[cch] = '\0';
1793 }
1794 else
1795 {
1796 strcpy(pszW, "/C \"");
1797 pszW += strlen(pszW);
1798 memcpy(pszW, psz2, cch);
1799 memcpy(pszW + cch, "\"\0", 3);
1800 }
1801
1802 return pszArg;
1803}
1804
1805
1806
1807/**
1808 * Normalizes the path slashes for the filename. It will partially expand paths too.
1809 * @returns pszFilename
1810 * @param pszFilename Pointer to filename string. Not empty string!
1811 * Much space to play with.
1812 * @remark (From fastdep.)
1813 * @remark BOGUS CODE! Recheck it please!
1814 */
1815char *fileNormalize(char *pszFilename, char *pszCurDir)
1816{
1817 char * pszRet = pszFilename;
1818 int aiSlashes[CCHMAXPATH/2];
1819 int cSlashes;
1820 int i;
1821
1822 /*
1823 * Init stuff.
1824 */
1825 for (i = 1, cSlashes = 0; pszCurDir[i] != '\0'; i++)
1826 {
1827 if (pszCurDir[i] == '/')
1828 pszCurDir[i] = '\\';
1829 if (pszCurDir[i] == '\\')
1830 aiSlashes[cSlashes++] = i;
1831 }
1832 if (pszCurDir[i-1] != '\\')
1833 {
1834 aiSlashes[cSlashes] = i;
1835 pszCurDir[i++] = '\\';
1836 pszCurDir[i] = '\0';
1837 }
1838
1839
1840 /* expand path? */
1841 if (pszFilename[1] != ':')
1842 { /* relative path */
1843 int iSlash;
1844 char szFile[CCHMAXPATH];
1845 char * psz = szFile;
1846
1847 strcpy(szFile, pszFilename);
1848 iSlash = *psz == '\\' ? 1 : cSlashes;
1849 while (*psz != '\0')
1850 {
1851 if (*psz == '.' && psz[1] == '.' && psz[2] == '\\')
1852 { /* up one directory */
1853 if (iSlash > 0)
1854 iSlash--;
1855 psz += 3;
1856 }
1857 else if (*psz == '.' && psz[1] == '\\')
1858 { /* no change */
1859 psz += 2;
1860 }
1861 else
1862 { /* completed expantion! */
1863 strncpy(pszFilename, pszCurDir, aiSlashes[iSlash]+1);
1864 strcpy(pszFilename + aiSlashes[iSlash]+1, psz);
1865 break;
1866 }
1867 }
1868 }
1869 /* else: assume full path */
1870
1871 return pszRet;
1872}
1873
1874/**
1875 * Checks if a given file exist.
1876 * @returns 0 if the file exists. (NO_ERROR)
1877 * 2 if the file doesn't exist. (ERROR_FILE_NOT_FOUND)
1878 * @param pszFilename Name of the file to check existance for.
1879 */
1880APIRET fileExist(const char *pszFilename)
1881{
1882 FILESTATUS3 fsts3;
1883 return DosQueryPathInfo((PSZ)pszFilename, FIL_STANDARD, &fsts3, sizeof(fsts3));
1884}
1885
1886
1887/**
1888 * Submits a command to the daemon.
1889 * @returns 0 on success.
1890 * -3 on failure.
1891 * @param rcIgnore Ignores returcodes ranging from 0 to rcIgnore.
1892 */
1893int Submit(int rcIgnore)
1894{
1895 int cch;
1896 int rc;
1897 char * psz;
1898 PPIB ppib;
1899 PTIB ptib;
1900
1901 DosGetInfoBlocks(&ptib, &ppib);
1902 rc = shrmemOpen();
1903 if (rc)
1904 return rc;
1905
1906 /*
1907 * Build message.
1908 */
1909 pShrMem->enmMsgType = msgSubmit;
1910 pShrMem->u1.Submit.rcIgnore = rcIgnore;
1911 _getcwd(pShrMem->u1.Submit.szCurrentDir, sizeof(pShrMem->u1.Submit.szCurrentDir));
1912
1913 /* command */
1914 psz = ppib->pib_pchcmd;
1915 psz += strlen(psz) + 1 + 7; /* 7 = strlen("submit ")*/
1916 while (*psz == ' ' || *psz == '\t')
1917 psz++;
1918 if (*psz == '-')
1919 {
1920 while (*psz != ' ' && *psz != '\t')
1921 psz++;
1922 while (*psz == ' ' || *psz == '\t')
1923 psz++;
1924 }
1925 cch = strlen(psz) + 1;
1926 if (cch > sizeof(pShrMem->u1.Submit.szCommand))
1927 {
1928 Error("Fatal error: Command too long.\n", rc);
1929 shrmemFree();
1930 return -1;
1931 }
1932 if (*psz == '"' && psz[cch-2] == '"') /* remove start & end quotes if any */
1933 {
1934 cch--;
1935 psz++;
1936 }
1937 memcpy(&pShrMem->u1.Submit.szCommand[0], psz, cch);
1938
1939 /* environment */
1940 for (cch = 1, psz = ppib->pib_pchenv; *psz != '\0';)
1941 {
1942 int cchVar = strlen(psz) + 1;
1943 cch += cchVar;
1944 psz += cchVar;
1945 }
1946 if ( ppib->pib_pchenv[cch-2] != '\0'
1947 || ppib->pib_pchenv[cch-1] != '\0')
1948 {
1949 Error("internal error\n");
1950 return -1;
1951 }
1952 if (cch > sizeof(pShrMem->u1.Submit.szzEnv))
1953 {
1954 Error("Fatal error: environment is to bit, cchEnv=%d\n", cch);
1955 shrmemFree();
1956 return -ERROR_BAD_ENVIRONMENT;
1957 }
1958 pShrMem->u1.Submit.cchEnv = cch;
1959 memcpy(&pShrMem->u1.Submit.szzEnv[0], ppib->pib_pchenv, cch);
1960
1961
1962 /*
1963 * Send message and get respons.
1964 */
1965 rc = shrmemSendClient(msgSubmitResponse);
1966 if (rc)
1967 {
1968 shrmemFree();
1969 return rc;
1970 }
1971
1972 rc = !pShrMem->u1.SubmitResponse.fRc;
1973 shrmemFree();
1974 return rc;
1975}
1976
1977
1978/**
1979 * Waits for the commands to complete.
1980 * Will write all output from completed command to stdout.
1981 * Will write failing commands last.
1982 * @returns Count of failing commands.
1983 */
1984int Wait(void)
1985{
1986 int rc;
1987
1988 rc = shrmemOpen();
1989 if (rc)
1990 return rc;
1991 do
1992 {
1993 pShrMem->enmMsgType = msgWait;
1994 pShrMem->u1.Wait.iNothing = 0;
1995 rc = shrmemSendClient(msgWaitResponse);
1996 if (rc)
1997 {
1998 shrmemFree();
1999 return -1;
2000 }
2001 printf("%s", pShrMem->u1.WaitResponse.szOutput);
2002 /*
2003 * Release the client mutex if more data and yield the CPU.
2004 * So we can submit more work. (Odin nmake lib...)
2005 */
2006 if (pShrMem->u1.WaitResponse.fMore)
2007 {
2008 DosReleaseMutexSem(pShrMem->hmtxClient);
2009 DosSleep(0);
2010 rc = DosRequestMutexSem(pShrMem->hmtxClient, SEM_INDEFINITE_WAIT);
2011 if (rc)
2012 {
2013 Error("Fatal error: failed to get client mutex. rc=%d\n", rc);
2014 shrmemFree();
2015 return -1;
2016 }
2017 }
2018 } while (pShrMem->u1.WaitResponse.fMore);
2019
2020 rc = pShrMem->u1.WaitResponse.rc;
2021 shrmemFree();
2022 return rc;
2023}
2024
2025
2026/**
2027 * Checks if the daemon is running.
2028 */
2029int QueryRunning(void)
2030{
2031 APIRET rc;
2032 rc = DosGetNamedSharedMem((PPVOID)(PVOID)&pShrMem,
2033 pszSharedMem,
2034 PAG_READ | PAG_WRITE);
2035 if (!rc)
2036 DosFreeMem(pShrMem);
2037
2038 return rc;
2039}
2040
2041
2042/**
2043 * Sends a kill command to the daemon to kill it and its workers.
2044 * @returns 0.
2045 */
2046int Kill(void)
2047{
2048 int rc;
2049
2050 rc = shrmemOpen();
2051 if (rc)
2052 return rc;
2053
2054 pShrMem->enmMsgType = msgKill;
2055 pShrMem->u1.Kill.iNothing = 0;
2056 rc = shrmemSendClient(msgKillResponse);
2057 if (!rc)
2058 rc = !pShrMem->u1.KillResponse.fRc;
2059
2060 shrmemFree();
2061 return rc;
2062}
2063
2064
2065/**
2066 * Shows the current queued commands.
2067 * Will write to stdout.
2068 * @returns 0 or -1 usually.
2069 */
2070int ShowJobs(void)
2071{
2072 int rc;
2073
2074 rc = shrmemOpen();
2075 if (rc)
2076 return rc;
2077 do
2078 {
2079 pShrMem->enmMsgType = msgShowJobs;
2080 pShrMem->u1.ShowJobs.iNothing = 0;
2081 rc = shrmemSendClient(msgShowJobsResponse);
2082 if (rc)
2083 {
2084 shrmemFree();
2085 return -1;
2086 }
2087 printf("%s", pShrMem->u1.ShowJobsResponse.szOutput);
2088 /*
2089 * Release the client mutex if more data and yield the CPU.
2090 * So we can submit more work. (Odin nmake lib...)
2091 */
2092 if (pShrMem->u1.ShowJobsResponse.fMore)
2093 {
2094 DosReleaseMutexSem(pShrMem->hmtxClient);
2095 DosSleep(0);
2096 rc = DosRequestMutexSem(pShrMem->hmtxClient, SEM_INDEFINITE_WAIT);
2097 if (rc)
2098 {
2099 Error("Fatal error: failed to get client mutex. rc=%d\n", rc);
2100 shrmemFree();
2101 return -1;
2102 }
2103 }
2104 } while (pShrMem->u1.ShowJobsResponse.fMore);
2105
2106 shrmemFree();
2107 return rc;
2108}
2109
2110
2111/**
2112 * Shows the current running jobs (not the output).
2113 * Will write to stdout.
2114 * @returns 0 or -1 usually.
2115 */
2116int ShowRunningJobs(void)
2117{
2118 int rc;
2119
2120 rc = shrmemOpen();
2121 if (rc)
2122 return rc;
2123 do
2124 {
2125 pShrMem->enmMsgType = msgShowRunningJobs;
2126 pShrMem->u1.ShowRunningJobs.iNothing = 0;
2127 rc = shrmemSendClient(msgShowRunningJobsResponse);
2128 if (rc)
2129 {
2130 shrmemFree();
2131 return -1;
2132 }
2133 printf("%s", pShrMem->u1.ShowRunningJobsResponse.szOutput);
2134 /*
2135 * Release the client mutex if more data and yield the CPU.
2136 * So we can submit more work. (Odin nmake lib...)
2137 */
2138 if (pShrMem->u1.ShowRunningJobsResponse.fMore)
2139 {
2140 DosReleaseMutexSem(pShrMem->hmtxClient);
2141 DosSleep(0);
2142 rc = DosRequestMutexSem(pShrMem->hmtxClient, SEM_INDEFINITE_WAIT);
2143 if (rc)
2144 {
2145 Error("Fatal error: failed to get client mutex. rc=%d\n", rc);
2146 shrmemFree();
2147 return -1;
2148 }
2149 }
2150 } while (pShrMem->u1.ShowRunningJobsResponse.fMore);
2151
2152 shrmemFree();
2153 return rc;
2154}
2155
2156
2157/**
2158 * Shows the current queue of successfully completed jobs (not the output).
2159 * Will write to stdout.
2160 * @returns 0 or -1 usually.
2161 */
2162int ShowCompletedJobs(void)
2163{
2164 int rc;
2165
2166 rc = shrmemOpen();
2167 if (rc)
2168 return rc;
2169 do
2170 {
2171 pShrMem->enmMsgType = msgShowCompletedJobs;
2172 pShrMem->u1.ShowCompletedJobs.iNothing = 0;
2173 rc = shrmemSendClient(msgShowCompletedJobsResponse);
2174 if (rc)
2175 {
2176 shrmemFree();
2177 return -1;
2178 }
2179 printf("%s", pShrMem->u1.ShowCompletedJobsResponse.szOutput);
2180 /*
2181 * Release the client mutex if more data and yield the CPU.
2182 * So we can submit more work. (Odin nmake lib...)
2183 */
2184 if (pShrMem->u1.ShowCompletedJobsResponse.fMore)
2185 {
2186 DosReleaseMutexSem(pShrMem->hmtxClient);
2187 DosSleep(0);
2188 rc = DosRequestMutexSem(pShrMem->hmtxClient, SEM_INDEFINITE_WAIT);
2189 if (rc)
2190 {
2191 Error("Fatal error: failed to get client mutex. rc=%d\n", rc);
2192 shrmemFree();
2193 return -1;
2194 }
2195 }
2196 } while (pShrMem->u1.ShowCompletedJobsResponse.fMore);
2197
2198 shrmemFree();
2199 return rc;
2200}
2201
2202
2203/**
2204 * Shows the current queue of failed jobs (not the output).
2205 * Will write to stdout.
2206 * @returns 0 or -1 usually.
2207 */
2208int ShowFailedJobs(void)
2209{
2210 int rc;
2211
2212 rc = shrmemOpen();
2213 if (rc)
2214 return rc;
2215 do
2216 {
2217 pShrMem->enmMsgType = msgShowFailedJobs;
2218 pShrMem->u1.ShowFailedJobs.iNothing = 0;
2219 rc = shrmemSendClient(msgShowFailedJobsResponse);
2220 if (rc)
2221 {
2222 shrmemFree();
2223 return -1;
2224 }
2225 printf("%s", pShrMem->u1.ShowFailedJobsResponse.szOutput);
2226 /*
2227 * Release the client mutex if more data and yield the CPU.
2228 * So we can submit more work. (Odin nmake lib...)
2229 */
2230 if (pShrMem->u1.ShowFailedJobsResponse.fMore)
2231 {
2232 DosReleaseMutexSem(pShrMem->hmtxClient);
2233 DosSleep(0);
2234 rc = DosRequestMutexSem(pShrMem->hmtxClient, SEM_INDEFINITE_WAIT);
2235 if (rc)
2236 {
2237 Error("Fatal error: failed to get client mutex. rc=%d\n", rc);
2238 shrmemFree();
2239 return -1;
2240 }
2241 }
2242 } while (pShrMem->u1.ShowFailedJobsResponse.fMore);
2243
2244 shrmemFree();
2245 return rc;
2246}
2247
2248
2249
2250/**
2251 * Creates the shared memory area.
2252 * The creator owns the memory when created.
2253 * @returns 0 on success. Error code on error.
2254 */
2255int shrmemCreate(void)
2256{
2257 int rc;
2258 rc = DosAllocSharedMem((PPVOID)(PVOID)&pShrMem,
2259 pszSharedMem,
2260 SHARED_MEM_SIZE,
2261 PAG_COMMIT | PAG_READ | PAG_WRITE);
2262 if (rc)
2263 {
2264 Error("Fatal error: Failed to create shared memory object. rc=%d\n", rc);
2265 return rc;
2266 }
2267
2268 rc = DosCreateEventSem(NULL, &pShrMem->hevDaemon, DC_SEM_SHARED, FALSE);
2269 if (rc)
2270 {
2271 Error("Fatal error: Failed to create daemon event semaphore. rc=%d\n", rc);
2272 DosFreeMem(pShrMem);
2273 return rc;
2274 }
2275
2276 rc = DosCreateEventSem(NULL, &pShrMem->hevClient, DC_SEM_SHARED, FALSE);
2277 if (rc)
2278 {
2279 Error("Fatal error: Failed to create client event semaphore. rc=%d\n", rc);
2280 DosCloseEventSem(pShrMem->hevDaemon);
2281 DosFreeMem(pShrMem);
2282 return rc;
2283 }
2284
2285 rc = DosCreateMutexSem(NULL, &pShrMem->hmtx, DC_SEM_SHARED, TRUE);
2286 if (rc)
2287 {
2288 Error("Fatal error: Failed to create mutex semaphore. rc=%d\n", rc);
2289 DosCloseEventSem(pShrMem->hevClient);
2290 DosCloseEventSem(pShrMem->hevDaemon);
2291 DosFreeMem(pShrMem);
2292 return rc;
2293 }
2294
2295 rc = DosCreateMutexSem(NULL, &pShrMem->hmtxClient, DC_SEM_SHARED, FALSE);
2296 if (rc)
2297 {
2298 Error("Fatal error: Failed to create client mutex semaphore. rc=%d\n", rc);
2299 DosCloseEventSem(pShrMem->hevClient);
2300 DosCloseEventSem(pShrMem->hevClient);
2301 DosCloseEventSem(pShrMem->hevDaemon);
2302 DosFreeMem(pShrMem);
2303 return rc;
2304 }
2305
2306
2307 /*
2308 * Install signal handlers.
2309 */
2310 signal(SIGSEGV, signalhandlerDaemon);
2311 signal(SIGTERM, signalhandlerDaemon);
2312 signal(SIGABRT, signalhandlerDaemon);
2313 signal(SIGINT, signalhandlerDaemon);
2314 signal(SIGBREAK,signalhandlerDaemon);
2315
2316 return rc;
2317}
2318
2319
2320/**
2321 * Opens the shared memory and the semaphores.
2322 * The caller is owner of the memory upon successful return.
2323 * @returns 0 on success. Error code on error.
2324 */
2325int shrmemOpen(void)
2326{
2327 int rc;
2328 ULONG ulIgnore;
2329
2330 /*
2331 * Get memory.
2332 */
2333 rc = DosGetNamedSharedMem((PPVOID)(PVOID)&pShrMem,
2334 pszSharedMem,
2335 PAG_READ | PAG_WRITE);
2336 if (rc)
2337 {
2338 Error("Fatal error: Failed to open shared memory. rc=%d\n", rc);
2339 return rc;
2340 }
2341
2342
2343 /*
2344 * Open semaphores.
2345 */
2346 rc = DosOpenEventSem(NULL, &pShrMem->hevClient);
2347 if (rc)
2348 {
2349 Error("Fatal error: Failed to open client event semaphore. rc=%d\n", rc);
2350 DosFreeMem(pShrMem);
2351 return rc;
2352 }
2353
2354 rc = DosOpenEventSem(NULL, &pShrMem->hevDaemon);
2355 if (rc)
2356 {
2357 Error("Fatal error: Failed to open daemon event semaphore. rc=%d\n", rc);
2358 DosCloseEventSem(pShrMem->hevClient);
2359 DosFreeMem(pShrMem);
2360 return rc;
2361 }
2362
2363 rc = DosOpenMutexSem(NULL, &pShrMem->hmtx);
2364 if (rc)
2365 {
2366 /* try correct client died situation */
2367 if (rc == ERROR_SEM_OWNER_DIED)
2368 {
2369 pShrMem->enmMsgType = msgSharedMemOwnerDied;
2370 DosResetEventSem(pShrMem->hevClient, &ulIgnore);
2371 DosPostEventSem(pShrMem->hevDaemon);
2372 if (DosWaitEventSem(pShrMem->hevClient, 2000))
2373 {
2374 Error("Fatal error: Failed to open mutex semaphore. (owner dead) rc=%d\n", rc);
2375 shrmemFree();
2376 return rc;
2377 }
2378 rc = DosOpenMutexSem(NULL, &pShrMem->hmtx);
2379 }
2380
2381 if (rc)
2382 {
2383 Error("Fatal error: Failed to open mutex semaphore. rc=%d\n", rc);
2384 DosCloseEventSem(pShrMem->hevClient);
2385 DosCloseEventSem(pShrMem->hevDaemon);
2386 DosFreeMem(pShrMem);
2387 return rc;
2388 }
2389 }
2390
2391 rc = DosOpenMutexSem(NULL, &pShrMem->hmtxClient);
2392 if (rc)
2393 {
2394 /* try correct client died situation */
2395 if (rc == ERROR_SEM_OWNER_DIED)
2396 {
2397 pShrMem->enmMsgType = msgClientOwnerDied;
2398 DosResetEventSem(pShrMem->hevClient, &ulIgnore);
2399 DosPostEventSem(pShrMem->hevDaemon);
2400 if (DosWaitEventSem(pShrMem->hevClient, 2000))
2401 {
2402 Error("Fatal error: Failed to open client mutex semaphore. (owner dead) rc=%d\n", rc);
2403 shrmemFree();
2404 return rc;
2405 }
2406 rc = DosOpenMutexSem(NULL, &pShrMem->hmtxClient);
2407 }
2408
2409 if (rc)
2410 {
2411 Error("Fatal error: Failed to open client mutex semaphore. rc=%d\n", rc);
2412 DosCloseEventSem(pShrMem->hevClient);
2413 DosCloseEventSem(pShrMem->hevDaemon);
2414 DosCloseMutexSem(pShrMem->hmtx);
2415 DosFreeMem(pShrMem);
2416 return rc;
2417 }
2418 }
2419
2420
2421 /*
2422 * Before we request semaphores we need to have signal handlers installed.
2423 */
2424 signal(SIGSEGV, signalhandlerClient);
2425 signal(SIGTERM, signalhandlerClient);
2426 signal(SIGABRT, signalhandlerClient);
2427 signal(SIGINT, signalhandlerClient);
2428 signal(SIGBREAK,signalhandlerClient);
2429
2430
2431 /*
2432 * Request the necessary semaphores to be able to talk to the daemon.
2433 */
2434 rc = DosRequestMutexSem(pShrMem->hmtxClient, SEM_INDEFINITE_WAIT);
2435 if (rc)
2436 {
2437 /* try correct client died situation */
2438 if (rc == ERROR_SEM_OWNER_DIED)
2439 {
2440 pShrMem->enmMsgType = msgClientOwnerDied;
2441 DosResetEventSem(pShrMem->hevClient, &ulIgnore);
2442 DosPostEventSem(pShrMem->hevDaemon);
2443 if (DosWaitEventSem(pShrMem->hevClient, 2000))
2444 {
2445 Error("Fatal error: Failed to take ownership of client mutex semaphore. (owner dead) rc=%d\n", rc);
2446 shrmemFree();
2447 return rc;
2448 }
2449 rc = DosRequestMutexSem(pShrMem->hmtxClient, SEM_INDEFINITE_WAIT);
2450 }
2451
2452 if (rc)
2453 {
2454 Error("Fatal error: Failed to take ownership of client mutex semaphore. rc=%d\n", rc);
2455 shrmemFree();
2456 return rc;
2457 }
2458 }
2459
2460 rc = DosRequestMutexSem(pShrMem->hmtx, SEM_INDEFINITE_WAIT);
2461 if (rc)
2462 {
2463 /* try correct client died situation */
2464 if (rc == ERROR_SEM_OWNER_DIED)
2465 {
2466 pShrMem->enmMsgType = msgSharedMemOwnerDied;
2467 DosResetEventSem(pShrMem->hevClient, &ulIgnore);
2468 DosPostEventSem(pShrMem->hevDaemon);
2469 if (DosWaitEventSem(pShrMem->hevClient, 2000))
2470 {
2471 Error("Fatal error: Failed to take ownership of mutex mutex semaphore. (owner dead) rc=%d\n", rc);
2472 shrmemFree();
2473 return rc;
2474 }
2475 rc = DosRequestMutexSem(pShrMem->hmtx, SEM_INDEFINITE_WAIT);
2476 }
2477
2478 if (rc)
2479 {
2480 Error("Fatal error: Failed to take ownership of mutex semaphore. rc=%d\n", rc);
2481 shrmemFree();
2482 return rc;
2483 }
2484 }
2485
2486
2487 return rc;
2488}
2489
2490
2491/**
2492 * Frees the shared memory and the associated semaphores.
2493 */
2494void shrmemFree(void)
2495{
2496 if (!pShrMem)
2497 return;
2498 /* wakeup any clients */
2499 DosPostEventSem(pShrMem->hevClient);
2500 /* free stuff */
2501 DosReleaseMutexSem(pShrMem->hmtxClient);
2502 DosReleaseMutexSem(pShrMem->hmtx);
2503 DosCloseMutexSem(pShrMem->hmtxClient);
2504 DosCloseMutexSem(pShrMem->hmtx);
2505 DosCloseEventSem(pShrMem->hevClient);
2506 DosCloseEventSem(pShrMem->hevDaemon);
2507 DosFreeMem(pShrMem);
2508 pShrMem = NULL;
2509}
2510
2511
2512/**
2513 * Daemon sends a message.
2514 * Upon we don't own the shared memory any longer.
2515 * @returns 0 on success. Error code on error.
2516 * -1 on timeout.
2517 * @param fWait Wait for new message.
2518 */
2519int shrmemSendDaemon(BOOL fWait)
2520{
2521 ULONG ulDummy;
2522 int rc;
2523
2524 /* send message */
2525 DosResetEventSem(pShrMem->hevDaemon, &ulDummy);
2526 rc = DosReleaseMutexSem(pShrMem->hmtx);
2527 if (!rc)
2528 rc = DosPostEventSem(pShrMem->hevClient);
2529
2530 /* wait for next message */
2531 if (!rc && fWait)
2532 {
2533 do
2534 {
2535 rc = DosWaitEventSem(pShrMem->hevDaemon, IDLE_TIMEOUT_MS);
2536 } while (rc == ERROR_TIMEOUT && pJobQueue);
2537
2538 if (rc == ERROR_TIMEOUT)
2539 {
2540 DosRequestMutexSem(pShrMem->hmtx, SEM_INDEFINITE_WAIT);
2541 shrmemFree();
2542 return -1;
2543 }
2544
2545 if (!rc)
2546 {
2547 rc = DosRequestMutexSem(pShrMem->hmtx, SEM_INDEFINITE_WAIT);
2548 if (rc == ERROR_SEM_OWNER_DIED)
2549 {
2550 DosCloseMutexSem(pShrMem->hmtx);
2551 pShrMem->hmtx = NULLHANDLE;
2552 rc = DosCreateMutexSem(NULL, &pShrMem->hmtx, DC_SEM_SHARED, TRUE);
2553 }
2554 }
2555
2556 if (rc && rc != ERROR_INTERRUPT)
2557 Error("Internal error: failed to get next message from daemon, rc=%d\n", rc);
2558 }
2559 else
2560 Error("Internal error: failed to send message from daemon, rc=%d\n", rc);
2561 return rc;
2562}
2563
2564
2565/**
2566 * Client sends a message.
2567 * Upon we don't own the shared memory any longer.
2568 * @returns 0 on success. Error code on error.
2569 * @param enmMsgTypeResponse The expected response on this message.
2570 */
2571int shrmemSendClient(int enmMsgTypeResponse)
2572{
2573 ULONG ulDummy;
2574 int rc;
2575
2576 /* send message */
2577 DosResetEventSem(pShrMem->hevClient, &ulDummy);
2578 rc = DosReleaseMutexSem(pShrMem->hmtx);
2579 if (!rc)
2580 rc = DosPostEventSem(pShrMem->hevDaemon);
2581
2582 /* wait for response */
2583 if (!rc)
2584 {
2585 rc = DosWaitEventSem(pShrMem->hevClient, SEM_INDEFINITE_WAIT);
2586 if (!rc)
2587 {
2588 rc = DosRequestMutexSem(pShrMem->hmtx, SEM_INDEFINITE_WAIT);
2589 if (rc == ERROR_SEM_OWNER_DIED)
2590 {
2591 Error("Internal error: shared mem mutex owner died.\n");
2592 return -1;
2593 }
2594
2595 if (!rc && pShrMem->enmMsgType != enmMsgTypeResponse)
2596 {
2597 if (pShrMem->enmMsgType != msgDying)
2598 Error("Internal error: Invalid response message. response=%d expected=%d\n",
2599 pShrMem->enmMsgType, enmMsgTypeResponse);
2600 else
2601 Error("Fatal error: daemon just died!\n");
2602 return -1;
2603 }
2604 }
2605 if (rc && rc != ERROR_INTERRUPT)
2606 Error("Internal error: failed to get response message from daemon, rc=%d\n", rc);
2607 }
2608 else
2609 Error("Internal error: failed to send message to daemon, rc=%d\n", rc);
2610
2611 return rc;
2612}
2613
2614
2615/**
2616 * printf lookalike used to print all run-tim errors.
2617 * @param pszFormat Format string.
2618 * @param ... Arguments (optional).
2619 */
2620void Error(const char *pszFormat, ...)
2621{
2622 va_list arg;
2623
2624 va_start(arg, pszFormat);
2625 vfprintf(stdout, pszFormat, arg);
2626 va_end(arg);
2627}
2628
2629
2630#ifdef DEBUGMEMORY
2631void my_free(void *pv)
2632{
2633 DosFreeMem((PVOID)((unsigned)pv & 0xffff0000));
2634}
2635
2636void *my_malloc(size_t cb)
2637{
2638 APIRET rc;
2639 PVOID pv;
2640 ULONG cbAlloc;
2641 char szMsg[200];
2642
2643 cbAlloc = (cb + 0x1fff) & (~0x0fff);
2644
2645 rc = DosAllocMem(&pv, cbAlloc, PAG_READ | PAG_WRITE);
2646 if (!rc)
2647 {
2648 rc = DosSetMem(pv, cbAlloc - 0x1000, PAG_READ | PAG_WRITE | PAG_COMMIT);
2649 if (rc)
2650 __interrupt(3);
2651 if (cb & 0xfff)
2652 pv = (PVOID)((unsigned)pv + 0x1000 - (cb & 0x0fff));
2653 }
2654
2655 strcpy(szMsg, "malloc(");
2656 _itoa(cb, szMsg + strlen(szMsg), 16);
2657 strcat(szMsg, ") -> ");
2658 _itoa(pv, szMsg + strlen(szMsg), 16);
2659 strcat(szMsg, "\r\n");
2660
2661 DosPutMessage(1, strlen(szMsg), szMsg);
2662
2663 return rc ? NULL : pv;
2664}
2665#endif
Note: See TracBrowser for help on using the repository browser.