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

Last change on this file since 8375 was 8375, checked in by bird, 23 years ago

Don't inherit std handles when starting the daemon. That hangs a tee'ed make job.

File size: 83.9 KB
Line 
1/* $Id: CmdQd.c,v 1.14 2002-05-07 09:18:09 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 DosSetFHState((HFILE)HF_STDIN, OPEN_FLAGS_NOINHERIT);
538 DosSetFHState((HFILE)HF_STDOUT, OPEN_FLAGS_NOINHERIT);
539 DosSetFHState((HFILE)HF_STDERR, OPEN_FLAGS_NOINHERIT);
540
541 sprintf(&szArg[0], "%s\t!Daemon! %d", arg0, cWorkers);
542 szArg[strlen(arg0)] = '\0';
543 rc = DosExecPgm(NULL, 0, EXEC_BACKGROUND, &szArg[0], NULL, &Res, &szArg[0]);
544 if (rc)
545 Error("Fatal error: Failed to start daemon. rc=%d\n", rc);
546 return rc;
547}
548
549
550/**
551 * This process is to be a daemon with a given number of works.
552 * @returns 0 on success.
553 * -4 on error.
554 * @param cWorkers Number of workers to start.
555 * @sketch
556 */
557int Daemon(int cWorkers)
558{
559 int rc;
560
561 /*
562 * Init Shared memory
563 */
564 rc = shrmemCreate();
565 if (rc)
566 return rc;
567
568 /*
569 * Init queues and semaphores.
570 */
571 rc = DaemonInit(cWorkers);
572 if (rc)
573 {
574 shrmemFree();
575 return rc;
576 }
577
578 /*
579 * Do work!
580 */
581 rc = shrmemSendDaemon(TRUE);
582 while (!rc)
583 {
584 switch (pShrMem->enmMsgType)
585 {
586 case msgSubmit:
587 {
588 PJOB pJob;
589
590 /*
591 * Make job entry.
592 */
593 pJob = malloc((int)&((PJOB)0)->JobInfo.szzEnv[pShrMem->u1.Submit.cchEnv]);
594 if (pJob)
595 {
596 memcpy(&pJob->JobInfo, &pShrMem->u1.Submit,
597 (int)&((struct Submit *)0)->szzEnv[pShrMem->u1.Submit.cchEnv]);
598 pJob->rc = -1;
599 pJob->pNext = NULL;
600 pJob->pJobOutput = NULL;
601
602 /*
603 * Insert the entry.
604 */
605 rc = DosRequestMutexSem(hmtxJobQueue, SEM_INDEFINITE_WAIT);
606 if (rc)
607 break;
608 if (!pJobQueue)
609 pJobQueueEnd = pJobQueue = pJob;
610 else
611 {
612 pJobQueueEnd->pNext = pJob;
613 pJobQueueEnd = pJob;
614 }
615 pJob->iJobId = cJobs++;
616 DosReleaseMutexSem(hmtxJobQueue);
617
618 /*
619 * Post the queue to wake up workers.
620 */
621 DosPostEventSem(hevJobQueue);
622 pShrMem->u1.SubmitResponse.fRc = TRUE;
623 }
624 else
625 {
626 Error("Internal Error: Out of memory (line=%d)\n", __LINE__);
627 pShrMem->u1.SubmitResponse.fRc = FALSE;
628 }
629 pShrMem->enmMsgType = msgSubmitResponse;
630 rc = shrmemSendDaemon(TRUE);
631 break;
632 }
633
634
635 case msgWait:
636 {
637 PJOB pJob = NULL;
638 PJOBOUTPUT pJobOutput = NULL;
639 char * psz;
640 int cch = 0;
641 char * pszOutput;
642 int cchOutput;
643 int rcFailure = 0;
644 BOOL fMore = TRUE;
645 ULONG ulIgnore;
646 void * pv;
647
648 DosPostEventSem(hevJobQueueFine); /* just so we don't get stuck in the loop... */
649 do
650 {
651 /* init response message */
652 pShrMem->enmMsgType = msgWaitResponse;
653 pShrMem->u1.WaitResponse.szOutput[0] = '\0';
654 pszOutput = &pShrMem->u1.WaitResponse.szOutput[0];
655 cchOutput = sizeof(pShrMem->u1.WaitResponse.szOutput) - 1;
656
657 /*
658 * Wait for output.
659 */
660 /*rc = DosWaitEventSem(hevJobQueueFine, SEM_INDEFINITE_WAIT); - there is some timing problem here, */
661 rc = DosWaitEventSem(hevJobQueueFine, 1000); /* timeout after 1 second. */
662 if (rc && rc != ERROR_TIMEOUT)
663 break;
664 rc = NO_ERROR; /* in case of TIMEOUT */
665
666 /*
667 * Copy output - Optimized so we don't cause to many context switches.
668 */
669 do
670 {
671 /*
672 * Next job.
673 */
674 if (!pJobOutput)
675 {
676 rc = DosRequestMutexSem(hmtxJobQueueFine, SEM_INDEFINITE_WAIT);
677 if (rc)
678 break;
679 pv = pJob;
680 pJob = pJobCompleted;
681 if (pJob)
682 {
683 pJobCompleted = pJob->pNext;
684 if (!pJobCompleted)
685 pJobCompletedLast = NULL;
686 }
687
688 if (!pJob && cJobs == cJobsFinished)
689 { /* all jobs finished, we may start output failures. */
690 pJob = pJobFailed;
691 if (pJob)
692 {
693 if (rcFailure == 0)
694 rcFailure = pJob->rc;
695
696 pJobFailed = pJob->pNext;
697 if (!pJobFailed)
698 pJobFailedLast = NULL;
699 }
700 else
701 fMore = FALSE;
702 }
703 else
704 DosResetEventSem(hevJobQueueFine, &ulIgnore); /* No more output, prepare wait. */
705 DosReleaseMutexSem(hmtxJobQueueFine);
706
707 if (pJob && pJob->pJobOutput)
708 {
709 pJobOutput = pJob->pJobOutput;
710 psz = pJobOutput->szOutput;
711 cch = pJobOutput->cchOutput;
712 }
713 if (pv)
714 free(pv);
715 }
716
717 /*
718 * Anything to output?
719 */
720 if (pJobOutput)
721 {
722 /*
723 * Copy output.
724 */
725 do
726 {
727 if (cch)
728 { /* copy */
729 int cchCopy = min(cch, cchOutput);
730 memcpy(pszOutput, psz, cchCopy);
731 psz += cchCopy; cch -= cchCopy;
732 pszOutput += cchCopy; cchOutput -= cchCopy;
733 }
734 if (!cch)
735 { /* next chunk */
736 pv = pJobOutput;
737 pJobOutput = pJobOutput->pNext;
738 if (pJobOutput)
739 {
740 psz = &pJobOutput->szOutput[0];
741 cch = pJobOutput->cchOutput;
742 }
743 free(pv);
744 }
745 } while (cch && cchOutput);
746 }
747 else
748 break; /* no more output, let's send what we got. */
749
750 } while (!rc && fMore && cchOutput);
751
752 /*
753 * We've got a message to send.
754 */
755 if (rc)
756 break;
757 *pszOutput = '\0';
758 pShrMem->u1.WaitResponse.rc = rcFailure;
759 pShrMem->u1.WaitResponse.fMore = fMore;
760 rc = shrmemSendDaemon(TRUE);
761 } while (!rc && fMore);
762
763 /*
764 * Check if the wait client died.
765 */
766 if (rc == ERROR_ALREADY_POSTED) /* seems like this is the rc we get. */
767 {
768 /*
769 * BUGBUG: This code is really fishy, but I'm to tired to make a real fix now.
770 * Hopefully this solves my current problem.
771 */
772 ULONG ulDummy;
773 rc = DosRequestMutexSem(pShrMem->hmtx, 500);
774 rc = DosResetEventSem(pShrMem->hevClient, &ulDummy);
775 pShrMem->enmMsgType = msgUnknown;
776 rc = shrmemSendDaemon(TRUE);
777 }
778 break;
779 }
780
781
782 case msgKill:
783 {
784 pShrMem->enmMsgType = msgKillResponse;
785 pShrMem->u1.KillResponse.fRc = TRUE;
786 shrmemSendDaemon(FALSE);
787 rc = -1;
788 break;
789 }
790
791
792 case msgShowJobs:
793 {
794 /*
795 * Gain access to the job list.
796 */
797 rc = DosRequestMutexSem(hmtxJobQueue, SEM_INDEFINITE_WAIT);
798 if (!rc)
799 {
800 int iJob = 0;
801 PJOB pJob = pJobQueue;
802
803 /*
804 * Big loop making and sending all messages.
805 */
806 do
807 {
808 int cch;
809 char * pszOutput;
810 int cchOutput;
811
812 /*
813 * Make one message.
814 */
815 pShrMem->enmMsgType = msgShowJobsResponse;
816 pszOutput = &pShrMem->u1.ShowJobsResponse.szOutput[0];
817 cchOutput = sizeof(pShrMem->u1.ShowJobsResponse.szOutput) - 1;
818
819 /*
820 * Insert job info.
821 */
822 while (pJob)
823 {
824 char szTmp[8192]; /* this is sufficient for one job. */
825
826 /*
827 * Format output in temporary buffer and check if
828 * it's space left in the share buffer.
829 */
830 cch = sprintf(szTmp,
831 "------------------ JobId %d - %d\n"
832 " command: %s\n"
833 " curdir: %s\n"
834 " rcIgnore: %d\n",
835 pJob->iJobId,
836 iJob,
837 pJob->JobInfo.szCommand,
838 pJob->JobInfo.szCurrentDir,
839 pJob->JobInfo.rcIgnore);
840 if (cch > cchOutput)
841 break;
842
843 /*
844 * Copy from temporary to shared buffer.
845 */
846 memcpy(pszOutput, szTmp, cch);
847 pszOutput += cch;
848 cchOutput -= cch;
849
850 /*
851 * Next job.
852 */
853 pJob = pJob->pNext;
854 iJob++;
855 }
856
857 /*
858 * Send the message.
859 */
860 *pszOutput = '\0';
861 pShrMem->u1.ShowJobsResponse.fMore = pJob != NULL;
862 if (!pJob)
863 DosReleaseMutexSem(hmtxJobQueue);
864 rc = shrmemSendDaemon(TRUE);
865
866 } while (!rc && pJob);
867
868
869 /*
870 * Release the job list.
871 */
872 DosReleaseMutexSem(hmtxJobQueue);
873 }
874 else
875 {
876 /* init response message */
877 pShrMem->enmMsgType = msgShowJobsResponse;
878 sprintf(&pShrMem->u1.ShowJobsResponse.szOutput[0],
879 "Internal Error. Requesting of hmtxJobQueue failed with rc=%d\n",
880 rc);
881 rc = shrmemSendDaemon(TRUE);
882 }
883
884
885 /*
886 * Check if the waiting client died.
887 */
888 if (rc == ERROR_ALREADY_POSTED) /* seems like this is the rc we get. */
889 {
890 /*
891 * BUGBUG: This code is really fishy, but I'm to tired to make a real fix now.
892 * Hopefully this solves my current problem.
893 */
894 ULONG ulDummy;
895 rc = DosRequestMutexSem(pShrMem->hmtx, 500);
896 rc = DosResetEventSem(pShrMem->hevClient, &ulDummy);
897 pShrMem->enmMsgType = msgUnknown;
898 rc = shrmemSendDaemon(TRUE);
899 }
900 break;
901 }
902
903
904 case msgShowFailedJobs:
905 {
906 /*
907 * Gain access to the finished job list.
908 */
909 rc = DosRequestMutexSem(hmtxJobQueueFine, SEM_INDEFINITE_WAIT);
910 if (!rc)
911 {
912 int iJob = 0;
913 PJOB pJob = pJobFailed;
914
915 /*
916 * Big loop making and sending all messages.
917 */
918 do
919 {
920 int cch;
921 char * pszOutput;
922 int cchOutput;
923
924 /*
925 * Make one message.
926 */
927 pShrMem->enmMsgType = msgShowFailedJobsResponse;
928 pszOutput = &pShrMem->u1.ShowFailedJobsResponse.szOutput[0];
929 cchOutput = sizeof(pShrMem->u1.ShowFailedJobsResponse.szOutput) - 1;
930
931 /*
932 * Insert job info.
933 */
934 while (pJob)
935 {
936 char szTmp[8192]; /* this is sufficient for one job. */
937
938 /*
939 * Format output in temporary buffer and check if
940 * it's space left in the share buffer.
941 */
942 cch = sprintf(szTmp,
943 "------------------ Failed JobId %d - %d\n"
944 " command: %s\n"
945 " curdir: %s\n"
946 " rc: %d (rcIgnore=%d)\n",
947 pJob->iJobId,
948 iJob,
949 pJob->JobInfo.szCommand,
950 pJob->JobInfo.szCurrentDir,
951 pJob->rc,
952 pJob->JobInfo.rcIgnore);
953 if (cch > cchOutput)
954 break;
955
956 /*
957 * Copy from temporary to shared buffer.
958 */
959 memcpy(pszOutput, szTmp, cch);
960 pszOutput += cch;
961 cchOutput -= cch;
962
963 /*
964 * Next job.
965 */
966 pJob = pJob->pNext;
967 iJob++;
968 }
969
970 /*
971 * Send the message.
972 */
973 *pszOutput = '\0';
974 pShrMem->u1.ShowFailedJobsResponse.fMore = pJob != NULL;
975 if (!pJob)
976 DosReleaseMutexSem(hmtxJobQueueFine);
977 rc = shrmemSendDaemon(TRUE);
978
979 } while (!rc && pJob);
980
981
982 /*
983 * Release the job list.
984 */
985 DosReleaseMutexSem(hmtxJobQueueFine);
986 }
987 else
988 {
989 /* init response message */
990 pShrMem->enmMsgType = msgShowFailedJobsResponse;
991 sprintf(&pShrMem->u1.ShowFailedJobsResponse.szOutput[0],
992 "Internal Error. Requesting of hmtxJobQueue failed with rc=%d\n",
993 rc);
994 rc = shrmemSendDaemon(TRUE);
995 }
996
997
998 /*
999 * Check if the waiting client died.
1000 */
1001 if (rc == ERROR_ALREADY_POSTED) /* seems like this is the rc we get. */
1002 {
1003 /*
1004 * BUGBUG: This code is really fishy, but I'm to tired to make a real fix now.
1005 * Hopefully this solves my current problem.
1006 */
1007 ULONG ulDummy;
1008 rc = DosRequestMutexSem(pShrMem->hmtx, 500);
1009 rc = DosResetEventSem(pShrMem->hevClient, &ulDummy);
1010 pShrMem->enmMsgType = msgUnknown;
1011 rc = shrmemSendDaemon(TRUE);
1012 }
1013 break;
1014 }
1015
1016
1017 case msgShowRunningJobs:
1018 {
1019 /*
1020 * Gain access to the job list.
1021 */
1022 rc = DosRequestMutexSem(hmtxJobQueue, SEM_INDEFINITE_WAIT);
1023 if (!rc)
1024 {
1025 int iJob = 0;
1026 PJOB pJob = pJobRunning;
1027
1028 /*
1029 * Big loop making and sending all messages.
1030 */
1031 do
1032 {
1033 int cch;
1034 char * pszOutput;
1035 int cchOutput;
1036
1037 /*
1038 * Make one message.
1039 */
1040 pShrMem->enmMsgType = msgShowRunningJobsResponse;
1041 pszOutput = &pShrMem->u1.ShowRunningJobsResponse.szOutput[0];
1042 cchOutput = sizeof(pShrMem->u1.ShowRunningJobsResponse.szOutput) - 1;
1043
1044 /*
1045 * Insert job info.
1046 */
1047 while (pJob)
1048 {
1049 char szTmp[8192]; /* this is sufficient for one job. */
1050
1051 /*
1052 * Format output in temporary buffer and check if
1053 * it's space left in the share buffer.
1054 */
1055 cch = sprintf(szTmp,
1056 "------------------ Running JobId %d - %d\n"
1057 " command: %s\n"
1058 " curdir: %s\n"
1059 " rcIgnore: %d\n",
1060 pJob->iJobId,
1061 iJob,
1062 pJob->JobInfo.szCommand,
1063 pJob->JobInfo.szCurrentDir,
1064 pJob->JobInfo.rcIgnore);
1065 if (cch > cchOutput)
1066 break;
1067
1068 /*
1069 * Copy from temporary to shared buffer.
1070 */
1071 memcpy(pszOutput, szTmp, cch);
1072 pszOutput += cch;
1073 cchOutput -= cch;
1074
1075 /*
1076 * Next job.
1077 */
1078 pJob = pJob->pNext;
1079 iJob++;
1080 }
1081
1082 /*
1083 * Send the message.
1084 */
1085 *pszOutput = '\0';
1086 pShrMem->u1.ShowRunningJobsResponse.fMore = pJob != NULL;
1087 if (!pJob)
1088 DosReleaseMutexSem(hmtxJobQueue);
1089 rc = shrmemSendDaemon(TRUE);
1090
1091 } while (!rc && pJob);
1092
1093
1094 /*
1095 * Release the job list.
1096 */
1097 DosReleaseMutexSem(hmtxJobQueue);
1098 }
1099 else
1100 {
1101 /* init response message */
1102 pShrMem->enmMsgType = msgShowRunningJobsResponse;
1103 sprintf(&pShrMem->u1.ShowRunningJobsResponse.szOutput[0],
1104 "Internal Error. Requesting of hmtxJobQueue failed with rc=%d\n",
1105 rc);
1106 rc = shrmemSendDaemon(TRUE);
1107 }
1108
1109
1110 /*
1111 * Check if the waiting client died.
1112 */
1113 if (rc == ERROR_ALREADY_POSTED) /* seems like this is the rc we get. */
1114 {
1115 /*
1116 * BUGBUG: This code is really fishy, but I'm to tired to make a real fix now.
1117 * Hopefully this solves my current problem.
1118 */
1119 ULONG ulDummy;
1120 rc = DosRequestMutexSem(pShrMem->hmtx, 500);
1121 rc = DosResetEventSem(pShrMem->hevClient, &ulDummy);
1122 pShrMem->enmMsgType = msgUnknown;
1123 rc = shrmemSendDaemon(TRUE);
1124 }
1125 break;
1126 }
1127
1128
1129
1130 case msgShowCompletedJobs:
1131 {
1132 /*
1133 * Gain access to the finished job list.
1134 */
1135 rc = DosRequestMutexSem(hmtxJobQueueFine, SEM_INDEFINITE_WAIT);
1136 if (!rc)
1137 {
1138 int iJob = 0;
1139 PJOB pJob = pJobCompleted;
1140
1141 /*
1142 * Big loop making and sending all messages.
1143 */
1144 do
1145 {
1146 int cch;
1147 char * pszOutput;
1148 int cchOutput;
1149
1150 /*
1151 * Make one message.
1152 */
1153 pShrMem->enmMsgType = msgShowCompletedJobsResponse;
1154 pszOutput = &pShrMem->u1.ShowCompletedJobsResponse.szOutput[0];
1155 cchOutput = sizeof(pShrMem->u1.ShowCompletedJobsResponse.szOutput) - 1;
1156
1157 /*
1158 * Insert job info.
1159 */
1160 while (pJob)
1161 {
1162 char szTmp[8192]; /* this is sufficient for one job. */
1163
1164 /*
1165 * Format output in temporary buffer and check if
1166 * it's space left in the share buffer.
1167 */
1168 cch = sprintf(szTmp,
1169 "------------------ Completed JobId %d - %d\n"
1170 " command: %s\n"
1171 " curdir: %s\n"
1172 " rcIgnore: %d\n",
1173 pJob->iJobId,
1174 iJob,
1175 pJob->JobInfo.szCommand,
1176 pJob->JobInfo.szCurrentDir,
1177 pJob->JobInfo.rcIgnore);
1178 if (cch > cchOutput)
1179 break;
1180
1181 /*
1182 * Copy from temporary to shared buffer.
1183 */
1184 memcpy(pszOutput, szTmp, cch);
1185 pszOutput += cch;
1186 cchOutput -= cch;
1187
1188 /*
1189 * Next job.
1190 */
1191 pJob = pJob->pNext;
1192 iJob++;
1193 }
1194
1195 /*
1196 * Send the message.
1197 */
1198 *pszOutput = '\0';
1199 pShrMem->u1.ShowCompletedJobsResponse.fMore = pJob != NULL;
1200 if (!pJob)
1201 DosReleaseMutexSem(hmtxJobQueueFine);
1202 rc = shrmemSendDaemon(TRUE);
1203
1204 } while (!rc && pJob);
1205
1206
1207 /*
1208 * Release the finished job list.
1209 */
1210 DosReleaseMutexSem(hmtxJobQueueFine);
1211 }
1212 else
1213 {
1214 /* init response message */
1215 pShrMem->enmMsgType = msgShowCompletedJobsResponse;
1216 sprintf(&pShrMem->u1.ShowCompletedJobsResponse.szOutput[0],
1217 "Internal Error. Requesting of hmtxJobQueue failed with rc=%d\n",
1218 rc);
1219 rc = shrmemSendDaemon(TRUE);
1220 }
1221
1222
1223 /*
1224 * Check if the waiting client died.
1225 */
1226 if (rc == ERROR_ALREADY_POSTED) /* seems like this is the rc we get. */
1227 {
1228 /*
1229 * BUGBUG: This code is really fishy, but I'm to tired to make a real fix now.
1230 * Hopefully this solves my current problem.
1231 */
1232 ULONG ulDummy;
1233 rc = DosRequestMutexSem(pShrMem->hmtx, 500);
1234 rc = DosResetEventSem(pShrMem->hevClient, &ulDummy);
1235 pShrMem->enmMsgType = msgUnknown;
1236 rc = shrmemSendDaemon(TRUE);
1237 }
1238 break;
1239 }
1240
1241
1242 case msgClientOwnerDied:
1243 {
1244 DosCloseMutexSem(pShrMem->hmtxClient);
1245 rc = DosCreateMutexSem(NULL, &pShrMem->hmtxClient, DC_SEM_SHARED, FALSE);
1246 if (rc)
1247 Error("Failed to restore dead client semaphore\n");
1248 pShrMem->enmMsgType = msgUnknown;
1249 rc = shrmemSendDaemon(TRUE);
1250 break;
1251 }
1252
1253
1254 case msgSharedMemOwnerDied:
1255 {
1256 DosCloseMutexSem(pShrMem->hmtx);
1257 rc = DosCreateMutexSem(NULL, &pShrMem->hmtx, DC_SEM_SHARED, TRUE);
1258 if (rc)
1259 Error("Failed to restore dead shared mem semaphore\n");
1260 pShrMem->enmMsgType = msgUnknown;
1261 rc = shrmemSendDaemon(TRUE);
1262 break;
1263 }
1264
1265
1266 default:
1267 Error("Internal error: Invalid message id %d\n", pShrMem->enmMsgType, rc);
1268 pShrMem->enmMsgType = msgUnknown;
1269 rc = shrmemSendDaemon(TRUE);
1270 }
1271 }
1272
1273 /*
1274 * Set dying msg type. shrmemFree posts the hevClient so clients
1275 * waiting for the daemon to respond will quit.
1276 */
1277 pShrMem->enmMsgType = msgDying;
1278
1279 /*
1280 * Cleanup.
1281 */
1282 shrmemFree();
1283 DosCloseMutexSem(hmtxJobQueue);
1284 DosCloseMutexSem(hmtxJobQueueFine);
1285 DosCloseEventSem(hevJobQueueFine);
1286 DosCloseMutexSem(hmtxExec);
1287 DosCloseEventSem(hevJobQueue);
1288
1289 return 0;
1290}
1291
1292
1293/**
1294 * Help which does most of the daemon init stuff.
1295 * @returns 0 on success.
1296 * @param cWorkers Number of worker threads to start.
1297 */
1298int DaemonInit(int cWorkers)
1299{
1300 int rc;
1301 int i;
1302
1303 /*
1304 * Init queues and semaphores.
1305 */
1306 rc = DosCreateEventSem(NULL, &hevJobQueue, 0, FALSE);
1307 if (!rc)
1308 {
1309 rc = DosCreateMutexSem(NULL, &hmtxJobQueue, 0, FALSE);
1310 if (!rc)
1311 {
1312 rc = DosCreateMutexSem(NULL, &hmtxJobQueueFine, 0, FALSE);
1313 if (!rc)
1314 {
1315 rc = DosCreateEventSem(NULL, &hevJobQueueFine, 0, FALSE);
1316 if (!rc)
1317 {
1318 rc = DosCreateMutexSem(NULL, &hmtxExec, 0, FALSE);
1319 if (!rc)
1320 {
1321 /*
1322 * Start workers.
1323 */
1324 rc = 0;
1325 for (i = 0; i < cWorkers; i++)
1326 if (_beginthread(Worker, NULL, 64*1024, (void*)i) == -1)
1327 {
1328 Error("Fatal error: failed to create worker thread no. %d\n", i);
1329 rc = -1;
1330 break;
1331 }
1332 if (!rc)
1333 {
1334 DosSetMaxFH(cWorkers * 6 + 20);
1335 return 0; /* success! */
1336 }
1337
1338 /* failure */
1339 DosCloseMutexSem(hmtxExec);
1340 }
1341 else
1342 Error("Fatal error: failed to create exec mutex. rc=%d", rc);
1343 DosCloseEventSem(hevJobQueueFine);
1344 }
1345 else
1346 Error("Fatal error: failed to create job queue fine event sem. rc=%d", rc);
1347 DosCloseMutexSem(hmtxJobQueueFine);
1348 }
1349 else
1350 Error("Fatal error: failed to create job queue fine mutex. rc=%d", rc);
1351 DosCloseMutexSem(hmtxJobQueue);
1352 }
1353 else
1354 Error("Fatal error: failed to create job queue mutex. rc=%d", rc);
1355 DosCloseEventSem(hevJobQueue);
1356 }
1357 else
1358 Error("Fatal error: failed to create job queue event sem. rc=%d", rc);
1359
1360 return rc;
1361}
1362
1363
1364/**
1365 * Daemon signal handler.
1366 */
1367void signalhandlerDaemon(int sig)
1368{
1369 /*
1370 * Set dying msg type. shrmemFree posts the hevClient so clients
1371 * waiting for the daemon to respond will quit.
1372 */
1373 pShrMem->enmMsgType = msgDying;
1374
1375 /*
1376 * Free and exit.
1377 */
1378 shrmemFree();
1379 exit(-42);
1380 sig = sig;
1381}
1382
1383
1384/**
1385 * Client signal handler.
1386 */
1387void signalhandlerClient(int sig)
1388{
1389 shrmemFree();
1390 exit(-42);
1391 sig = sig;
1392}
1393
1394
1395
1396/**
1397 * Worker thread.
1398 * @param iWorkerId The worker process id.
1399 * @sketch
1400 */
1401void Worker(void * iWorkerId)
1402{
1403 PATHCACHE PathCache;
1404 memset(&PathCache, 0, sizeof(PathCache));
1405
1406 while (!DosWaitEventSem(hevJobQueue, SEM_INDEFINITE_WAIT))
1407 {
1408 PJOB pJob;
1409
1410 /*
1411 * Get job.
1412 */
1413 if (DosRequestMutexSem(hmtxJobQueue, SEM_INDEFINITE_WAIT))
1414 return;
1415 pJob = pJobQueue;
1416 if (pJob)
1417 {
1418 /* remove from input queue */
1419 if (pJob != pJobQueueEnd)
1420 pJobQueue = pJob->pNext;
1421 else
1422 {
1423 ULONG ulIgnore;
1424 pJobQueue = pJobQueueEnd = NULL;
1425 DosResetEventSem(hevJobQueue, &ulIgnore);
1426 }
1427
1428 /* insert into running */
1429 pJob->pNext = NULL;
1430 if (pJobRunningEnd)
1431 pJobRunningEnd = pJobRunningEnd->pNext = pJob;
1432 else
1433 pJobRunning = pJobRunningEnd = pJob;
1434 }
1435 DosReleaseMutexSem(hmtxJobQueue);
1436
1437 /*
1438 * Execute job.
1439 */
1440 if (pJob)
1441 {
1442 int rc;
1443 char szArg[4096];
1444 char szObj[256];
1445 PJOBOUTPUT pJobOutput = NULL;
1446 PJOBOUTPUT pJobOutputLast = NULL;
1447 RESULTCODES Res;
1448 PID pid;
1449 HFILE hStdOut = HF_STDOUT;
1450 HFILE hStdErr = HF_STDERR;
1451 HFILE hStdOutSave = -1;
1452 HFILE hStdErrSave = -1;
1453 HPIPE hPipeR = NULLHANDLE;
1454 HPIPE hPipeW = NULLHANDLE;
1455
1456 //printf("debug-%d: start %s\n", iWorkerId, pJob->JobInfo.szCommand);
1457
1458 /*
1459 * Redirect output and start process.
1460 */
1461 WorkerArguments(&szArg[0], &pJob->JobInfo.szzEnv[0], &pJob->JobInfo.szCommand[0],
1462 &pJob->JobInfo.szCurrentDir[0], &PathCache);
1463 rc = DosCreatePipe(&hPipeR, &hPipeW, sizeof(pJobOutput->szOutput) - 1);
1464 if (rc)
1465 {
1466 Error("Internal Error: Failed to create pipe! rc=%d\n", rc);
1467 return;
1468 }
1469
1470 if (DosRequestMutexSem(hmtxExec, SEM_INDEFINITE_WAIT))
1471 {
1472 DosClose(hPipeR);
1473 DosClose(hPipeW);
1474 return;
1475 }
1476
1477 pJob->pJobOutput = pJobOutput = pJobOutputLast = malloc(sizeof(JOBOUTPUT));
1478 pJobOutput->pNext = NULL;
1479 pJobOutput->cchOutput = sprintf(pJobOutput->szOutput, "Job: %s\n", pJob->JobInfo.szCommand);
1480
1481 rc = DosSetDefaultDisk( pJob->JobInfo.szCurrentDir[0] >= 'a'
1482 ? pJob->JobInfo.szCurrentDir[0] - 'a' + 1
1483 : pJob->JobInfo.szCurrentDir[0] - 'A' + 1);
1484 rc += DosSetCurrentDir(pJob->JobInfo.szCurrentDir);
1485 if (!rc)
1486 {
1487 assert( pJob->JobInfo.szzEnv[pJob->JobInfo.cchEnv-1] == '\0'
1488 && pJob->JobInfo.szzEnv[pJob->JobInfo.cchEnv-2] == '\0');
1489 DosDupHandle(HF_STDOUT, &hStdOutSave);
1490 DosDupHandle(HF_STDERR, &hStdErrSave);
1491 DosDupHandle(hPipeW, &hStdOut);
1492 DosDupHandle(hPipeW, &hStdErr);
1493 rc = DosExecPgm(szObj, sizeof(szObj), EXEC_ASYNCRESULT,
1494 szArg, pJob->JobInfo.szzEnv, &Res, szArg);
1495 DosClose(hStdOut); hStdOut = HF_STDOUT;
1496 DosClose(hStdErr); hStdErr = HF_STDERR;
1497 DosDupHandle(hStdOutSave, &hStdOut);
1498 DosDupHandle(hStdErrSave, &hStdErr);
1499 DosClose(hStdOutSave);
1500 DosClose(hStdErrSave);
1501 DosReleaseMutexSem(hmtxExec);
1502 DosClose(hPipeW);
1503
1504
1505 /*
1506 * Read Output.
1507 */
1508 if (!rc)
1509 {
1510 ULONG cchRead;
1511 ULONG cchRead2 = 0;
1512
1513 cchRead = sizeof(pJobOutput->szOutput) - pJobOutput->cchOutput - 1;
1514 while (((rc = DosRead(hPipeR,
1515 &pJobOutput->szOutput[pJobOutput->cchOutput],
1516 cchRead, &cchRead2)) == NO_ERROR
1517 || rc == ERROR_MORE_DATA)
1518 && cchRead2 != 0)
1519 {
1520 pJobOutput->cchOutput += cchRead2;
1521 pJobOutput->szOutput[pJobOutput->cchOutput] = '\0';
1522
1523 /* prepare next read */
1524 cchRead = sizeof(pJobOutput->szOutput) - pJobOutput->cchOutput - 1;
1525 if (cchRead < 16)
1526 {
1527 pJobOutput = pJobOutput->pNext = malloc(sizeof(JOBOUTPUT));
1528 pJobOutput->pNext = NULL;
1529 pJobOutput->cchOutput = 0;
1530 cchRead = sizeof(pJobOutput->szOutput) - 1;
1531 }
1532 cchRead2 = 0;
1533 }
1534 rc = 0;
1535 }
1536
1537 /* finished reading */
1538 DosClose(hPipeR);
1539
1540 /*
1541 * Get result.
1542 */
1543 if (!rc)
1544 {
1545 DosWaitChild(DCWA_PROCESS, DCWW_WAIT, &Res, &pid, Res.codeTerminate);
1546 if ( Res.codeResult <= pJob->JobInfo.rcIgnore
1547 && Res.codeTerminate == TC_EXIT)
1548 pJob->rc = 0;
1549 else
1550 {
1551 pJob->rc = -1;
1552 rc = sprintf(szArg, "failed with rc=%d term=%d\n", Res.codeResult, Res.codeTerminate);
1553 if (rc + pJobOutput->cchOutput + 1 >= sizeof(pJobOutput->szOutput))
1554 {
1555 pJobOutput = pJobOutput->pNext = malloc(sizeof(JOBOUTPUT));
1556 pJobOutput->pNext = NULL;
1557 pJobOutput->cchOutput = 0;
1558 }
1559 strcpy(&pJobOutput->szOutput[pJobOutput->cchOutput], szArg);
1560 pJobOutput->cchOutput += rc;
1561 }
1562 }
1563 else
1564 {
1565 pJobOutput->cchOutput += sprintf(&pJobOutput->szOutput[pJobOutput->cchOutput],
1566 "DosExecPgm failed with rc=%d for command %s %s\n"
1567 " obj=%s\n",
1568 rc, szArg, pJob->JobInfo.szCommand, szObj);
1569 pJob->rc = -1;
1570 }
1571 }
1572 else
1573 {
1574 /*
1575 * ChDir failed.
1576 */
1577 DosReleaseMutexSem(hmtxExec);
1578 pJobOutput->cchOutput += sprintf(&pJobOutput->szOutput[pJobOutput->cchOutput ],
1579 "Failed to set current directory to: %s (rc=%d)\n",
1580 pJob->JobInfo.szCurrentDir, rc);
1581 pJob->rc = -1;
1582 DosClose(hPipeR);
1583 }
1584
1585
1586 /*
1587 * Remove from the running queue.
1588 */
1589 if (DosRequestMutexSem(hmtxJobQueue, SEM_INDEFINITE_WAIT))
1590 return;
1591
1592 if (pJobRunning != pJob)
1593 {
1594 PJOB pJobCur = pJobRunning;
1595 while (pJobCur)
1596 {
1597 if (pJobCur->pNext == pJob)
1598 {
1599 pJobCur->pNext = pJob->pNext;
1600 if (pJob == pJobRunningEnd)
1601 pJobRunningEnd = pJobCur;
1602 break;
1603 }
1604 pJobCur = pJobCur->pNext;
1605 }
1606 }
1607 else
1608 pJobRunning = pJobRunningEnd = NULL;
1609
1610 DosReleaseMutexSem(hmtxJobQueue);
1611
1612
1613 /*
1614 * Insert result in result queue.
1615 */
1616 if (DosRequestMutexSem(hmtxJobQueueFine, SEM_INDEFINITE_WAIT))
1617 return;
1618 pJob->pNext = NULL;
1619 if (!pJob->rc) /* 0 on success. */
1620 {
1621 if (pJobCompletedLast)
1622 pJobCompletedLast->pNext = pJob;
1623 else
1624 pJobCompleted = pJob;
1625 pJobCompletedLast = pJob;
1626 }
1627 else
1628 {
1629 if (pJobFailedLast)
1630 pJobFailedLast->pNext = pJob;
1631 else
1632 pJobFailed = pJob;
1633 pJobFailedLast = pJob;
1634 }
1635 cJobsFinished++;
1636 DosReleaseMutexSem(hmtxJobQueueFine);
1637 /* wake up Wait. */
1638 DosPostEventSem(hevJobQueueFine);
1639 //printf("debug-%d: fine\n", iWorkerId);
1640 }
1641 }
1642 iWorkerId = iWorkerId;
1643}
1644
1645
1646/**
1647 * Builds the input to DosExecPgm.
1648 * Will execute programs directly and command thru the shell.
1649 *
1650 * @returns pszArg.
1651 * @param pszArg Arguments to DosExecPgm.(output)
1652 * Assumes that the buffer is large enought.
1653 * @param pszzEnv Pointer to environment block.
1654 * @param pszCommand Command to execute.
1655 * @param pszCurDir From where the command is to executed.
1656 * @param pPathCache Used to cache the last path, executable, and the search result.
1657 */
1658char *WorkerArguments(char *pszArg, const char *pszzEnv, const char *pszCommand, char *pszCurDir, PPATHCACHE pPathCache)
1659{
1660 BOOL fCMD = FALSE;
1661 const char *psz;
1662 const char *psz2;
1663 char * pszW;
1664 char ch;
1665 int cch;
1666 APIRET rc;
1667
1668 /*
1669 * Check if this is multiple command separated by either &, && or |.
1670 * Currently ignoring quotes for this test.
1671 */
1672 if ( strchr(pszCommand, '&')
1673 || strchr(pszCommand, '|')
1674 || strchr(pszCommand, '@'))
1675 {
1676 strcpy(pszArg, "cmd.exe"); /* doesn't use comspec, just defaults to cmd.exe in all cases. */
1677 fCMD = TRUE;
1678 psz2 = pszCommand; /* start of arguments. */
1679 }
1680 else
1681 {
1682 char chEnd = ' ';
1683
1684 /*
1685 * Parse out the first name.
1686 */
1687 for (psz = pszCommand; *psz == '\t' || *psz == ' ';) //strip(,'L');
1688 psz++;
1689 if (*psz == '"' || *psz == '\'')
1690 chEnd = *psz++;
1691 psz2 = psz;
1692 if (chEnd == ' ')
1693 {
1694 while ((ch = *psz) != '\0' && ch != ' ' && ch != '\t')
1695 psz++;
1696 }
1697 else
1698 {
1699 while ((ch = *psz) != '\0' && ch != chEnd)
1700 psz++;
1701 }
1702 *pszArg = '\0';
1703 strncat(pszArg, psz2, psz - psz2);
1704 psz2 = psz+1; /* start of arguments. */
1705 }
1706
1707
1708 /*
1709 * Resolve the executable name if not qualified.
1710 * NB! We doesn't fully support references to other driveletters yet. (TODO/BUGBUG)
1711 */
1712 /* correct slashes */
1713 pszW = pszArg;
1714 while ((pszW = strchr(pszW, '//')) != NULL)
1715 *pszW++ = '\\';
1716
1717 /* make sure it ends with .exe */
1718 pszW = pszArg + strlen(pszArg) - 1;
1719 while (pszW > pszArg && *pszW != '.' && *pszW != '\\')
1720 pszW--;
1721 if (*pszW != '.')
1722 strcat(pszArg, ".exe");
1723
1724 if (pszArg[1] != ':' || *pszArg == *pszCurDir)
1725 {
1726 rc = -1; /* indicate that we've not found the file. */
1727
1728 /* relative path? - expand it */
1729 if (strchr(pszArg, '\\') || pszArg[1] == ':')
1730 { /* relative path - expand it and check for file existence */
1731 fileNormalize(pszArg, pszCurDir);
1732 pszCurDir[strlen(pszCurDir)-1] = '\0'; /* remove slash */
1733 rc = fileExist(pszArg);
1734 }
1735 else
1736 { /* Search path. */
1737 const char *pszPath = pszzEnv;
1738 while (*pszPath != '\0' && strncmp(pszPath, "PATH=", 5))
1739 pszPath += strlen(pszPath) + 1;
1740
1741 if (pszPath && *pszPath != '\0')
1742 {
1743 /* check cache */
1744 if ( !strcmp(pPathCache->szProgram, pszArg)
1745 && !strcmp(pPathCache->szPath, pszPath)
1746 && !strcmp(pPathCache->szCurDir, pszCurDir)
1747 )
1748 {
1749 strcpy(pszArg, pPathCache->szResult);
1750 rc = fileExist(pszArg);
1751 }
1752
1753 if (rc)
1754 { /* search path */
1755 char szResult[CCHMAXPATH];
1756 rc = DosSearchPath(SEARCH_IGNORENETERRS, (PSZ)pszPath, pszArg, &szResult[0] , sizeof(szResult));
1757 if (!rc)
1758 {
1759 strcpy(pszArg, szResult);
1760
1761 /* update cache */
1762 strcpy(pPathCache->szProgram, pszArg);
1763 strcpy(pPathCache->szPath, pszPath);
1764 strcpy(pPathCache->szCurDir, pszCurDir);
1765 strcpy(pPathCache->szResult, szResult);
1766 }
1767 }
1768 }
1769 }
1770 }
1771 /* else nothing to do - assume full path (btw. we don't have the current dir for other drives anyway :-) */
1772 else
1773 rc = !fCMD ? fileExist(pszArg) : NO_ERROR;
1774
1775 /* In case of error use CMD */
1776 if (rc && !fCMD)
1777 {
1778 strcpy(pszArg, "cmd.exe"); /* doesn't use comspec, just defaults to cmd.exe in all cases. */
1779 fCMD = TRUE;
1780 psz2 = pszCommand; /* start of arguments. */
1781 }
1782
1783
1784 /*
1785 * Complete the argument string.
1786 * ---
1787 * szArg current holds the command.
1788 * psz2 points to the first parameter. (needs strip(,'L'))
1789 */
1790 while ((ch = *psz2) != '\0' && (ch == '\t' || ch == ' '))
1791 psz2++;
1792
1793 pszW = pszArg + strlen(pszArg) + 1;
1794 cch = strlen(psz2);
1795 if (!fCMD)
1796 {
1797 memcpy(pszW, psz2, ++cch);
1798 pszW[cch] = '\0';
1799 }
1800 else
1801 {
1802 strcpy(pszW, "/C \"");
1803 pszW += strlen(pszW);
1804 memcpy(pszW, psz2, cch);
1805 memcpy(pszW + cch, "\"\0", 3);
1806 }
1807
1808 return pszArg;
1809}
1810
1811
1812
1813/**
1814 * Normalizes the path slashes for the filename. It will partially expand paths too.
1815 * @returns pszFilename
1816 * @param pszFilename Pointer to filename string. Not empty string!
1817 * Much space to play with.
1818 * @remark (From fastdep.)
1819 * @remark BOGUS CODE! Recheck it please!
1820 */
1821char *fileNormalize(char *pszFilename, char *pszCurDir)
1822{
1823 char * pszRet = pszFilename;
1824 int aiSlashes[CCHMAXPATH/2];
1825 int cSlashes;
1826 int i;
1827
1828 /*
1829 * Init stuff.
1830 */
1831 for (i = 1, cSlashes = 0; pszCurDir[i] != '\0'; i++)
1832 {
1833 if (pszCurDir[i] == '/')
1834 pszCurDir[i] = '\\';
1835 if (pszCurDir[i] == '\\')
1836 aiSlashes[cSlashes++] = i;
1837 }
1838 if (pszCurDir[i-1] != '\\')
1839 {
1840 aiSlashes[cSlashes] = i;
1841 pszCurDir[i++] = '\\';
1842 pszCurDir[i] = '\0';
1843 }
1844
1845
1846 /* expand path? */
1847 if (pszFilename[1] != ':')
1848 { /* relative path */
1849 int iSlash;
1850 char szFile[CCHMAXPATH];
1851 char * psz = szFile;
1852
1853 strcpy(szFile, pszFilename);
1854 iSlash = *psz == '\\' ? 1 : cSlashes;
1855 while (*psz != '\0')
1856 {
1857 if (*psz == '.' && psz[1] == '.' && psz[2] == '\\')
1858 { /* up one directory */
1859 if (iSlash > 0)
1860 iSlash--;
1861 psz += 3;
1862 }
1863 else if (*psz == '.' && psz[1] == '\\')
1864 { /* no change */
1865 psz += 2;
1866 }
1867 else
1868 { /* completed expantion! */
1869 strncpy(pszFilename, pszCurDir, aiSlashes[iSlash]+1);
1870 strcpy(pszFilename + aiSlashes[iSlash]+1, psz);
1871 break;
1872 }
1873 }
1874 }
1875 /* else: assume full path */
1876
1877 return pszRet;
1878}
1879
1880/**
1881 * Checks if a given file exist.
1882 * @returns 0 if the file exists. (NO_ERROR)
1883 * 2 if the file doesn't exist. (ERROR_FILE_NOT_FOUND)
1884 * @param pszFilename Name of the file to check existance for.
1885 */
1886APIRET fileExist(const char *pszFilename)
1887{
1888 FILESTATUS3 fsts3;
1889 return DosQueryPathInfo((PSZ)pszFilename, FIL_STANDARD, &fsts3, sizeof(fsts3));
1890}
1891
1892
1893/**
1894 * Submits a command to the daemon.
1895 * @returns 0 on success.
1896 * -3 on failure.
1897 * @param rcIgnore Ignores returcodes ranging from 0 to rcIgnore.
1898 */
1899int Submit(int rcIgnore)
1900{
1901 int cch;
1902 int rc;
1903 char * psz;
1904 PPIB ppib;
1905 PTIB ptib;
1906
1907 DosGetInfoBlocks(&ptib, &ppib);
1908 rc = shrmemOpen();
1909 if (rc)
1910 return rc;
1911
1912 /*
1913 * Build message.
1914 */
1915 pShrMem->enmMsgType = msgSubmit;
1916 pShrMem->u1.Submit.rcIgnore = rcIgnore;
1917 _getcwd(pShrMem->u1.Submit.szCurrentDir, sizeof(pShrMem->u1.Submit.szCurrentDir));
1918
1919 /* command */
1920 psz = ppib->pib_pchcmd;
1921 psz += strlen(psz) + 1 + 7; /* 7 = strlen("submit ")*/
1922 while (*psz == ' ' || *psz == '\t')
1923 psz++;
1924 if (*psz == '-')
1925 {
1926 while (*psz != ' ' && *psz != '\t')
1927 psz++;
1928 while (*psz == ' ' || *psz == '\t')
1929 psz++;
1930 }
1931 cch = strlen(psz) + 1;
1932 if (cch > sizeof(pShrMem->u1.Submit.szCommand))
1933 {
1934 Error("Fatal error: Command too long.\n", rc);
1935 shrmemFree();
1936 return -1;
1937 }
1938 if (*psz == '"' && psz[cch-2] == '"') /* remove start & end quotes if any */
1939 {
1940 cch--;
1941 psz++;
1942 }
1943 memcpy(&pShrMem->u1.Submit.szCommand[0], psz, cch);
1944
1945 /* environment */
1946 for (cch = 1, psz = ppib->pib_pchenv; *psz != '\0';)
1947 {
1948 int cchVar = strlen(psz) + 1;
1949 cch += cchVar;
1950 psz += cchVar;
1951 }
1952 if ( ppib->pib_pchenv[cch-2] != '\0'
1953 || ppib->pib_pchenv[cch-1] != '\0')
1954 {
1955 Error("internal error\n");
1956 return -1;
1957 }
1958 if (cch > sizeof(pShrMem->u1.Submit.szzEnv))
1959 {
1960 Error("Fatal error: environment is to bit, cchEnv=%d\n", cch);
1961 shrmemFree();
1962 return -ERROR_BAD_ENVIRONMENT;
1963 }
1964 pShrMem->u1.Submit.cchEnv = cch;
1965 memcpy(&pShrMem->u1.Submit.szzEnv[0], ppib->pib_pchenv, cch);
1966
1967
1968 /*
1969 * Send message and get respons.
1970 */
1971 rc = shrmemSendClient(msgSubmitResponse);
1972 if (rc)
1973 {
1974 shrmemFree();
1975 return rc;
1976 }
1977
1978 rc = !pShrMem->u1.SubmitResponse.fRc;
1979 shrmemFree();
1980 return rc;
1981}
1982
1983
1984/**
1985 * Waits for the commands to complete.
1986 * Will write all output from completed command to stdout.
1987 * Will write failing commands last.
1988 * @returns Count of failing commands.
1989 */
1990int Wait(void)
1991{
1992 int rc;
1993
1994 rc = shrmemOpen();
1995 if (rc)
1996 return rc;
1997 do
1998 {
1999 pShrMem->enmMsgType = msgWait;
2000 pShrMem->u1.Wait.iNothing = 0;
2001 rc = shrmemSendClient(msgWaitResponse);
2002 if (rc)
2003 {
2004 shrmemFree();
2005 return -1;
2006 }
2007 printf("%s", pShrMem->u1.WaitResponse.szOutput);
2008 /*
2009 * Release the client mutex if more data and yield the CPU.
2010 * So we can submit more work. (Odin nmake lib...)
2011 */
2012 if (pShrMem->u1.WaitResponse.fMore)
2013 {
2014 DosReleaseMutexSem(pShrMem->hmtxClient);
2015 DosSleep(0);
2016 rc = DosRequestMutexSem(pShrMem->hmtxClient, SEM_INDEFINITE_WAIT);
2017 if (rc)
2018 {
2019 Error("Fatal error: failed to get client mutex. rc=%d\n", rc);
2020 shrmemFree();
2021 return -1;
2022 }
2023 }
2024 } while (pShrMem->u1.WaitResponse.fMore);
2025
2026 rc = pShrMem->u1.WaitResponse.rc;
2027 shrmemFree();
2028 return rc;
2029}
2030
2031
2032/**
2033 * Checks if the daemon is running.
2034 */
2035int QueryRunning(void)
2036{
2037 APIRET rc;
2038 rc = DosGetNamedSharedMem((PPVOID)(PVOID)&pShrMem,
2039 pszSharedMem,
2040 PAG_READ | PAG_WRITE);
2041 if (!rc)
2042 DosFreeMem(pShrMem);
2043
2044 return rc;
2045}
2046
2047
2048/**
2049 * Sends a kill command to the daemon to kill it and its workers.
2050 * @returns 0.
2051 */
2052int Kill(void)
2053{
2054 int rc;
2055
2056 rc = shrmemOpen();
2057 if (rc)
2058 return rc;
2059
2060 pShrMem->enmMsgType = msgKill;
2061 pShrMem->u1.Kill.iNothing = 0;
2062 rc = shrmemSendClient(msgKillResponse);
2063 if (!rc)
2064 rc = !pShrMem->u1.KillResponse.fRc;
2065
2066 shrmemFree();
2067 return rc;
2068}
2069
2070
2071/**
2072 * Shows the current queued commands.
2073 * Will write to stdout.
2074 * @returns 0 or -1 usually.
2075 */
2076int ShowJobs(void)
2077{
2078 int rc;
2079
2080 rc = shrmemOpen();
2081 if (rc)
2082 return rc;
2083 do
2084 {
2085 pShrMem->enmMsgType = msgShowJobs;
2086 pShrMem->u1.ShowJobs.iNothing = 0;
2087 rc = shrmemSendClient(msgShowJobsResponse);
2088 if (rc)
2089 {
2090 shrmemFree();
2091 return -1;
2092 }
2093 printf("%s", pShrMem->u1.ShowJobsResponse.szOutput);
2094 /*
2095 * Release the client mutex if more data and yield the CPU.
2096 * So we can submit more work. (Odin nmake lib...)
2097 */
2098 if (pShrMem->u1.ShowJobsResponse.fMore)
2099 {
2100 DosReleaseMutexSem(pShrMem->hmtxClient);
2101 DosSleep(0);
2102 rc = DosRequestMutexSem(pShrMem->hmtxClient, SEM_INDEFINITE_WAIT);
2103 if (rc)
2104 {
2105 Error("Fatal error: failed to get client mutex. rc=%d\n", rc);
2106 shrmemFree();
2107 return -1;
2108 }
2109 }
2110 } while (pShrMem->u1.ShowJobsResponse.fMore);
2111
2112 shrmemFree();
2113 return rc;
2114}
2115
2116
2117/**
2118 * Shows the current running jobs (not the output).
2119 * Will write to stdout.
2120 * @returns 0 or -1 usually.
2121 */
2122int ShowRunningJobs(void)
2123{
2124 int rc;
2125
2126 rc = shrmemOpen();
2127 if (rc)
2128 return rc;
2129 do
2130 {
2131 pShrMem->enmMsgType = msgShowRunningJobs;
2132 pShrMem->u1.ShowRunningJobs.iNothing = 0;
2133 rc = shrmemSendClient(msgShowRunningJobsResponse);
2134 if (rc)
2135 {
2136 shrmemFree();
2137 return -1;
2138 }
2139 printf("%s", pShrMem->u1.ShowRunningJobsResponse.szOutput);
2140 /*
2141 * Release the client mutex if more data and yield the CPU.
2142 * So we can submit more work. (Odin nmake lib...)
2143 */
2144 if (pShrMem->u1.ShowRunningJobsResponse.fMore)
2145 {
2146 DosReleaseMutexSem(pShrMem->hmtxClient);
2147 DosSleep(0);
2148 rc = DosRequestMutexSem(pShrMem->hmtxClient, SEM_INDEFINITE_WAIT);
2149 if (rc)
2150 {
2151 Error("Fatal error: failed to get client mutex. rc=%d\n", rc);
2152 shrmemFree();
2153 return -1;
2154 }
2155 }
2156 } while (pShrMem->u1.ShowRunningJobsResponse.fMore);
2157
2158 shrmemFree();
2159 return rc;
2160}
2161
2162
2163/**
2164 * Shows the current queue of successfully completed jobs (not the output).
2165 * Will write to stdout.
2166 * @returns 0 or -1 usually.
2167 */
2168int ShowCompletedJobs(void)
2169{
2170 int rc;
2171
2172 rc = shrmemOpen();
2173 if (rc)
2174 return rc;
2175 do
2176 {
2177 pShrMem->enmMsgType = msgShowCompletedJobs;
2178 pShrMem->u1.ShowCompletedJobs.iNothing = 0;
2179 rc = shrmemSendClient(msgShowCompletedJobsResponse);
2180 if (rc)
2181 {
2182 shrmemFree();
2183 return -1;
2184 }
2185 printf("%s", pShrMem->u1.ShowCompletedJobsResponse.szOutput);
2186 /*
2187 * Release the client mutex if more data and yield the CPU.
2188 * So we can submit more work. (Odin nmake lib...)
2189 */
2190 if (pShrMem->u1.ShowCompletedJobsResponse.fMore)
2191 {
2192 DosReleaseMutexSem(pShrMem->hmtxClient);
2193 DosSleep(0);
2194 rc = DosRequestMutexSem(pShrMem->hmtxClient, SEM_INDEFINITE_WAIT);
2195 if (rc)
2196 {
2197 Error("Fatal error: failed to get client mutex. rc=%d\n", rc);
2198 shrmemFree();
2199 return -1;
2200 }
2201 }
2202 } while (pShrMem->u1.ShowCompletedJobsResponse.fMore);
2203
2204 shrmemFree();
2205 return rc;
2206}
2207
2208
2209/**
2210 * Shows the current queue of failed jobs (not the output).
2211 * Will write to stdout.
2212 * @returns 0 or -1 usually.
2213 */
2214int ShowFailedJobs(void)
2215{
2216 int rc;
2217
2218 rc = shrmemOpen();
2219 if (rc)
2220 return rc;
2221 do
2222 {
2223 pShrMem->enmMsgType = msgShowFailedJobs;
2224 pShrMem->u1.ShowFailedJobs.iNothing = 0;
2225 rc = shrmemSendClient(msgShowFailedJobsResponse);
2226 if (rc)
2227 {
2228 shrmemFree();
2229 return -1;
2230 }
2231 printf("%s", pShrMem->u1.ShowFailedJobsResponse.szOutput);
2232 /*
2233 * Release the client mutex if more data and yield the CPU.
2234 * So we can submit more work. (Odin nmake lib...)
2235 */
2236 if (pShrMem->u1.ShowFailedJobsResponse.fMore)
2237 {
2238 DosReleaseMutexSem(pShrMem->hmtxClient);
2239 DosSleep(0);
2240 rc = DosRequestMutexSem(pShrMem->hmtxClient, SEM_INDEFINITE_WAIT);
2241 if (rc)
2242 {
2243 Error("Fatal error: failed to get client mutex. rc=%d\n", rc);
2244 shrmemFree();
2245 return -1;
2246 }
2247 }
2248 } while (pShrMem->u1.ShowFailedJobsResponse.fMore);
2249
2250 shrmemFree();
2251 return rc;
2252}
2253
2254
2255
2256/**
2257 * Creates the shared memory area.
2258 * The creator owns the memory when created.
2259 * @returns 0 on success. Error code on error.
2260 */
2261int shrmemCreate(void)
2262{
2263 int rc;
2264 rc = DosAllocSharedMem((PPVOID)(PVOID)&pShrMem,
2265 pszSharedMem,
2266 SHARED_MEM_SIZE,
2267 PAG_COMMIT | PAG_READ | PAG_WRITE);
2268 if (rc)
2269 {
2270 Error("Fatal error: Failed to create shared memory object. rc=%d\n", rc);
2271 return rc;
2272 }
2273
2274 rc = DosCreateEventSem(NULL, &pShrMem->hevDaemon, DC_SEM_SHARED, FALSE);
2275 if (rc)
2276 {
2277 Error("Fatal error: Failed to create daemon event semaphore. rc=%d\n", rc);
2278 DosFreeMem(pShrMem);
2279 return rc;
2280 }
2281
2282 rc = DosCreateEventSem(NULL, &pShrMem->hevClient, DC_SEM_SHARED, FALSE);
2283 if (rc)
2284 {
2285 Error("Fatal error: Failed to create client event semaphore. rc=%d\n", rc);
2286 DosCloseEventSem(pShrMem->hevDaemon);
2287 DosFreeMem(pShrMem);
2288 return rc;
2289 }
2290
2291 rc = DosCreateMutexSem(NULL, &pShrMem->hmtx, DC_SEM_SHARED, TRUE);
2292 if (rc)
2293 {
2294 Error("Fatal error: Failed to create mutex semaphore. rc=%d\n", rc);
2295 DosCloseEventSem(pShrMem->hevClient);
2296 DosCloseEventSem(pShrMem->hevDaemon);
2297 DosFreeMem(pShrMem);
2298 return rc;
2299 }
2300
2301 rc = DosCreateMutexSem(NULL, &pShrMem->hmtxClient, DC_SEM_SHARED, FALSE);
2302 if (rc)
2303 {
2304 Error("Fatal error: Failed to create client mutex semaphore. rc=%d\n", rc);
2305 DosCloseEventSem(pShrMem->hevClient);
2306 DosCloseEventSem(pShrMem->hevClient);
2307 DosCloseEventSem(pShrMem->hevDaemon);
2308 DosFreeMem(pShrMem);
2309 return rc;
2310 }
2311
2312
2313 /*
2314 * Install signal handlers.
2315 */
2316 signal(SIGSEGV, signalhandlerDaemon);
2317 signal(SIGTERM, signalhandlerDaemon);
2318 signal(SIGABRT, signalhandlerDaemon);
2319 signal(SIGINT, signalhandlerDaemon);
2320 signal(SIGBREAK,signalhandlerDaemon);
2321
2322 return rc;
2323}
2324
2325
2326/**
2327 * Opens the shared memory and the semaphores.
2328 * The caller is owner of the memory upon successful return.
2329 * @returns 0 on success. Error code on error.
2330 */
2331int shrmemOpen(void)
2332{
2333 int rc;
2334 ULONG ulIgnore;
2335
2336 /*
2337 * Get memory.
2338 */
2339 rc = DosGetNamedSharedMem((PPVOID)(PVOID)&pShrMem,
2340 pszSharedMem,
2341 PAG_READ | PAG_WRITE);
2342 if (rc)
2343 {
2344 Error("Fatal error: Failed to open shared memory. rc=%d\n", rc);
2345 return rc;
2346 }
2347
2348
2349 /*
2350 * Open semaphores.
2351 */
2352 rc = DosOpenEventSem(NULL, &pShrMem->hevClient);
2353 if (rc)
2354 {
2355 Error("Fatal error: Failed to open client event semaphore. rc=%d\n", rc);
2356 DosFreeMem(pShrMem);
2357 return rc;
2358 }
2359
2360 rc = DosOpenEventSem(NULL, &pShrMem->hevDaemon);
2361 if (rc)
2362 {
2363 Error("Fatal error: Failed to open daemon event semaphore. rc=%d\n", rc);
2364 DosCloseEventSem(pShrMem->hevClient);
2365 DosFreeMem(pShrMem);
2366 return rc;
2367 }
2368
2369 rc = DosOpenMutexSem(NULL, &pShrMem->hmtx);
2370 if (rc)
2371 {
2372 /* try correct client died situation */
2373 if (rc == ERROR_SEM_OWNER_DIED)
2374 {
2375 pShrMem->enmMsgType = msgSharedMemOwnerDied;
2376 DosResetEventSem(pShrMem->hevClient, &ulIgnore);
2377 DosPostEventSem(pShrMem->hevDaemon);
2378 if (DosWaitEventSem(pShrMem->hevClient, 2000))
2379 {
2380 Error("Fatal error: Failed to open mutex semaphore. (owner dead) rc=%d\n", rc);
2381 shrmemFree();
2382 return rc;
2383 }
2384 rc = DosOpenMutexSem(NULL, &pShrMem->hmtx);
2385 }
2386
2387 if (rc)
2388 {
2389 Error("Fatal error: Failed to open mutex semaphore. rc=%d\n", rc);
2390 DosCloseEventSem(pShrMem->hevClient);
2391 DosCloseEventSem(pShrMem->hevDaemon);
2392 DosFreeMem(pShrMem);
2393 return rc;
2394 }
2395 }
2396
2397 rc = DosOpenMutexSem(NULL, &pShrMem->hmtxClient);
2398 if (rc)
2399 {
2400 /* try correct client died situation */
2401 if (rc == ERROR_SEM_OWNER_DIED)
2402 {
2403 pShrMem->enmMsgType = msgClientOwnerDied;
2404 DosResetEventSem(pShrMem->hevClient, &ulIgnore);
2405 DosPostEventSem(pShrMem->hevDaemon);
2406 if (DosWaitEventSem(pShrMem->hevClient, 2000))
2407 {
2408 Error("Fatal error: Failed to open client mutex semaphore. (owner dead) rc=%d\n", rc);
2409 shrmemFree();
2410 return rc;
2411 }
2412 rc = DosOpenMutexSem(NULL, &pShrMem->hmtxClient);
2413 }
2414
2415 if (rc)
2416 {
2417 Error("Fatal error: Failed to open client mutex semaphore. rc=%d\n", rc);
2418 DosCloseEventSem(pShrMem->hevClient);
2419 DosCloseEventSem(pShrMem->hevDaemon);
2420 DosCloseMutexSem(pShrMem->hmtx);
2421 DosFreeMem(pShrMem);
2422 return rc;
2423 }
2424 }
2425
2426
2427 /*
2428 * Before we request semaphores we need to have signal handlers installed.
2429 */
2430 signal(SIGSEGV, signalhandlerClient);
2431 signal(SIGTERM, signalhandlerClient);
2432 signal(SIGABRT, signalhandlerClient);
2433 signal(SIGINT, signalhandlerClient);
2434 signal(SIGBREAK,signalhandlerClient);
2435
2436
2437 /*
2438 * Request the necessary semaphores to be able to talk to the daemon.
2439 */
2440 rc = DosRequestMutexSem(pShrMem->hmtxClient, SEM_INDEFINITE_WAIT);
2441 if (rc)
2442 {
2443 /* try correct client died situation */
2444 if (rc == ERROR_SEM_OWNER_DIED)
2445 {
2446 pShrMem->enmMsgType = msgClientOwnerDied;
2447 DosResetEventSem(pShrMem->hevClient, &ulIgnore);
2448 DosPostEventSem(pShrMem->hevDaemon);
2449 if (DosWaitEventSem(pShrMem->hevClient, 2000))
2450 {
2451 Error("Fatal error: Failed to take ownership of client mutex semaphore. (owner dead) rc=%d\n", rc);
2452 shrmemFree();
2453 return rc;
2454 }
2455 rc = DosRequestMutexSem(pShrMem->hmtxClient, SEM_INDEFINITE_WAIT);
2456 }
2457
2458 if (rc)
2459 {
2460 Error("Fatal error: Failed to take ownership of client mutex semaphore. rc=%d\n", rc);
2461 shrmemFree();
2462 return rc;
2463 }
2464 }
2465
2466 rc = DosRequestMutexSem(pShrMem->hmtx, SEM_INDEFINITE_WAIT);
2467 if (rc)
2468 {
2469 /* try correct client died situation */
2470 if (rc == ERROR_SEM_OWNER_DIED)
2471 {
2472 pShrMem->enmMsgType = msgSharedMemOwnerDied;
2473 DosResetEventSem(pShrMem->hevClient, &ulIgnore);
2474 DosPostEventSem(pShrMem->hevDaemon);
2475 if (DosWaitEventSem(pShrMem->hevClient, 2000))
2476 {
2477 Error("Fatal error: Failed to take ownership of mutex mutex semaphore. (owner dead) rc=%d\n", rc);
2478 shrmemFree();
2479 return rc;
2480 }
2481 rc = DosRequestMutexSem(pShrMem->hmtx, SEM_INDEFINITE_WAIT);
2482 }
2483
2484 if (rc)
2485 {
2486 Error("Fatal error: Failed to take ownership of mutex semaphore. rc=%d\n", rc);
2487 shrmemFree();
2488 return rc;
2489 }
2490 }
2491
2492
2493 return rc;
2494}
2495
2496
2497/**
2498 * Frees the shared memory and the associated semaphores.
2499 */
2500void shrmemFree(void)
2501{
2502 if (!pShrMem)
2503 return;
2504 /* wakeup any clients */
2505 DosPostEventSem(pShrMem->hevClient);
2506 /* free stuff */
2507 DosReleaseMutexSem(pShrMem->hmtxClient);
2508 DosReleaseMutexSem(pShrMem->hmtx);
2509 DosCloseMutexSem(pShrMem->hmtxClient);
2510 DosCloseMutexSem(pShrMem->hmtx);
2511 DosCloseEventSem(pShrMem->hevClient);
2512 DosCloseEventSem(pShrMem->hevDaemon);
2513 DosFreeMem(pShrMem);
2514 pShrMem = NULL;
2515}
2516
2517
2518/**
2519 * Daemon sends a message.
2520 * Upon we don't own the shared memory any longer.
2521 * @returns 0 on success. Error code on error.
2522 * -1 on timeout.
2523 * @param fWait Wait for new message.
2524 */
2525int shrmemSendDaemon(BOOL fWait)
2526{
2527 ULONG ulDummy;
2528 int rc;
2529
2530 /* send message */
2531 DosResetEventSem(pShrMem->hevDaemon, &ulDummy);
2532 rc = DosReleaseMutexSem(pShrMem->hmtx);
2533 if (!rc)
2534 rc = DosPostEventSem(pShrMem->hevClient);
2535
2536 /* wait for next message */
2537 if (!rc && fWait)
2538 {
2539 do
2540 {
2541 rc = DosWaitEventSem(pShrMem->hevDaemon, IDLE_TIMEOUT_MS);
2542 } while (rc == ERROR_TIMEOUT && pJobQueue);
2543
2544 if (rc == ERROR_TIMEOUT)
2545 {
2546 DosRequestMutexSem(pShrMem->hmtx, SEM_INDEFINITE_WAIT);
2547 shrmemFree();
2548 return -1;
2549 }
2550
2551 if (!rc)
2552 {
2553 rc = DosRequestMutexSem(pShrMem->hmtx, SEM_INDEFINITE_WAIT);
2554 if (rc == ERROR_SEM_OWNER_DIED)
2555 {
2556 DosCloseMutexSem(pShrMem->hmtx);
2557 pShrMem->hmtx = NULLHANDLE;
2558 rc = DosCreateMutexSem(NULL, &pShrMem->hmtx, DC_SEM_SHARED, TRUE);
2559 }
2560 }
2561
2562 if (rc && rc != ERROR_INTERRUPT)
2563 Error("Internal error: failed to get next message from daemon, rc=%d\n", rc);
2564 }
2565 else
2566 Error("Internal error: failed to send message from daemon, rc=%d\n", rc);
2567 return rc;
2568}
2569
2570
2571/**
2572 * Client sends a message.
2573 * Upon we don't own the shared memory any longer.
2574 * @returns 0 on success. Error code on error.
2575 * @param enmMsgTypeResponse The expected response on this message.
2576 */
2577int shrmemSendClient(int enmMsgTypeResponse)
2578{
2579 ULONG ulDummy;
2580 int rc;
2581
2582 /* send message */
2583 DosResetEventSem(pShrMem->hevClient, &ulDummy);
2584 rc = DosReleaseMutexSem(pShrMem->hmtx);
2585 if (!rc)
2586 rc = DosPostEventSem(pShrMem->hevDaemon);
2587
2588 /* wait for response */
2589 if (!rc)
2590 {
2591 rc = DosWaitEventSem(pShrMem->hevClient, SEM_INDEFINITE_WAIT);
2592 if (!rc)
2593 {
2594 rc = DosRequestMutexSem(pShrMem->hmtx, SEM_INDEFINITE_WAIT);
2595 if (rc == ERROR_SEM_OWNER_DIED)
2596 {
2597 Error("Internal error: shared mem mutex owner died.\n");
2598 return -1;
2599 }
2600
2601 if (!rc && pShrMem->enmMsgType != enmMsgTypeResponse)
2602 {
2603 if (pShrMem->enmMsgType != msgDying)
2604 Error("Internal error: Invalid response message. response=%d expected=%d\n",
2605 pShrMem->enmMsgType, enmMsgTypeResponse);
2606 else
2607 Error("Fatal error: daemon just died!\n");
2608 return -1;
2609 }
2610 }
2611 if (rc && rc != ERROR_INTERRUPT)
2612 Error("Internal error: failed to get response message from daemon, rc=%d\n", rc);
2613 }
2614 else
2615 Error("Internal error: failed to send message to daemon, rc=%d\n", rc);
2616
2617 return rc;
2618}
2619
2620
2621/**
2622 * printf lookalike used to print all run-tim errors.
2623 * @param pszFormat Format string.
2624 * @param ... Arguments (optional).
2625 */
2626void Error(const char *pszFormat, ...)
2627{
2628 va_list arg;
2629
2630 va_start(arg, pszFormat);
2631 vfprintf(stdout, pszFormat, arg);
2632 va_end(arg);
2633}
2634
2635
2636#ifdef DEBUGMEMORY
2637void my_free(void *pv)
2638{
2639 DosFreeMem((PVOID)((unsigned)pv & 0xffff0000));
2640}
2641
2642void *my_malloc(size_t cb)
2643{
2644 APIRET rc;
2645 PVOID pv;
2646 ULONG cbAlloc;
2647 char szMsg[200];
2648
2649 cbAlloc = (cb + 0x1fff) & (~0x0fff);
2650
2651 rc = DosAllocMem(&pv, cbAlloc, PAG_READ | PAG_WRITE);
2652 if (!rc)
2653 {
2654 rc = DosSetMem(pv, cbAlloc - 0x1000, PAG_READ | PAG_WRITE | PAG_COMMIT);
2655 if (rc)
2656 __interrupt(3);
2657 if (cb & 0xfff)
2658 pv = (PVOID)((unsigned)pv + 0x1000 - (cb & 0x0fff));
2659 }
2660
2661 strcpy(szMsg, "malloc(");
2662 _itoa(cb, szMsg + strlen(szMsg), 16);
2663 strcat(szMsg, ") -> ");
2664 _itoa(pv, szMsg + strlen(szMsg), 16);
2665 strcat(szMsg, "\r\n");
2666
2667 DosPutMessage(1, strlen(szMsg), szMsg);
2668
2669 return rc ? NULL : pv;
2670}
2671#endif
Note: See TracBrowser for help on using the repository browser.