Debian Codegraph @

generic/bltBgexec.c

raw symbols ◀ ▶ SCIP
3 Debian patches touch this file
1 /*
2 * bltBgexec.c --
3 *
4 * This module implements a background "exec" command for the
5 * BLT toolkit.
6 *
7 * Copyright 1993-1998 Lucent Technologies, Inc.
8 *
9 * Permission to use, copy, modify, and distribute this software and
10 * its documentation for any purpose and without fee is hereby
11 * granted, provided that the above copyright notice appear in all
12 * copies and that both that the copyright notice and warranty
13 * disclaimer appear in supporting documentation, and that the names
14 * of Lucent Technologies any of their entities not be used in
15 * advertising or publicity pertaining to distribution of the software
16 * without specific, written prior permission.
17 *
18 * Lucent Technologies disclaims all warranties with regard to this
19 * software, including all implied warranties of merchantability and
20 * fitness. In no event shall Lucent Technologies be liable for any
21 * special, indirect or consequential damages or any damages
22 * whatsoever resulting from loss of use, data or profits, whether in
23 * an action of contract, negligence or other tortuous action, arising
24 * out of or in connection with the use or performance of this
25 * software.
26 *
27 * The "bgexec" command was created by George Howlett.
28 */
29
30 #include "bltInt.h"
31
32 #ifndef NO_BGEXEC
33
34 #include <fcntl.h>
35 #include <signal.h>
36 #ifdef HAVE_SYS_PARAM_H
37 #include <sys/param.h>
38 #endif
39 #include <sys/types.h>
40
41 #include "bltWait.h"
42 #include "bltSwitch.h"
43
44 #if (TCL_MAJOR_VERSION == 7)
45 #define FILEHANDLER_USES_TCLFILES 1
46 #else
47 typedef int Tcl_File;
48 #endif
49
50 static Tcl_CmdProc BgexecCmd;
51
52 #ifdef WIN32
53 typedef struct {
54 DWORD pid;
55 HANDLE hProcess;
56 } Process;
57 #else
58 typedef int Process;
59 #endif
60
61 #if (TCL_VERSION_NUMBER < _VERSION(8,1,0))
62 typedef void *Tcl_Encoding; /* Make up dummy type for encoding. */
63 #endif
64
65 #define ENCODING_ASCII ((Tcl_Encoding)NULL)
66 #define ENCODING_BINARY ((Tcl_Encoding)1)
67
68 /*
69 * As of Tcl 7.6, we're using our own version of the old
70 * Tcl_CreatePipeline routine. I would have tried to use
71 * Tcl_OpenCommandChannel but you can't get at the array of
72 * process ids, unless of course you pry open the undocumented
73 * structure PipeStatus as clientData. Nor could I figure out
74 * how to set one side of the pipe to be non-blocking. The whole
75 * channel API seems overly complex for what its supposed to
76 * do. [And maybe that's why it keeps changing every release.]
77 */
78 extern int Blt_CreatePipeline _ANSI_ARGS_((Tcl_Interp *interp, int argc,
79 char **argv, Process **pidPtrPtr, int *inPipePtr, int *outPipePtr,
80 int *errFilePtr));
81
82 #ifdef WIN32
83 #define read(fd, buf, size) Blt_AsyncRead((fd),(buf),(size))
84 #define close(fd) CloseHandle((HANDLE)fd)
85 #define Tcl_CreateFileHandler Blt_CreateFileHandler
86 #define Tcl_DeleteFileHandler Blt_DeleteFileHandler
87 #define kill KillProcess
88 #define waitpid WaitProcess
89 #endif
90
91 #define EXPECTED_NUM_TIMERS 4
92
93 #define READ_AGAIN (0)
94 #define READ_EOF (-1)
95 #define READ_ERROR (-2)
96
97 /* The wait-related definitions are taken from tclUnix.h */
98
99 #define TRACE_FLAGS (TCL_TRACE_WRITES | TCL_TRACE_UNSETS | TCL_GLOBAL_ONLY)
100
101 #define BLOCK_SIZE 1024 /* Size of allocation blocks for buffer */
102 #define DEF_BUFFER_SIZE (BLOCK_SIZE * 8)
103 #define MAX_READS 100 /* Maximum number of successful reads
104 * before stopping to let Tcl catch up
105 * on events */
106
107 #ifndef NSIG
108 #define NSIG 32 /* Number of signals available */
109 #endif /*NSIG*/
110
111 #ifndef SIGINT
112 #define SIGINT 2
113 #endif /* SIGINT */
114
115 #ifndef SIGQUIT
116 #define SIGQUIT 3
117 #endif /* SIGQUIT */
118
119 #ifndef SIGKILL
120 #define SIGKILL 9
121 #endif /* SIGKILL */
122
123 #ifndef SIGTERM
124 #define SIGTERM 14
125 #endif /* SIGTERM */
126
127 typedef struct {
128 int number;
129 char *name;
130 } SignalId;
131
132 static SignalId signalIds[] =
133 {
134 #ifdef SIGABRT
135 {SIGABRT, "SIGABRT"},
136 #endif
137 #ifdef SIGALRM
138 {SIGALRM, "SIGALRM"},
139 #endif
140 #ifdef SIGBUS
141 {SIGBUS, "SIGBUS"},
142 #endif
143 #ifdef SIGCHLD
144 {SIGCHLD, "SIGCHLD"},
145 #endif
146 #if defined(SIGCLD) && (!defined(SIGCHLD) || (SIGCLD != SIGCHLD))
147 {SIGCLD, "SIGCLD"},
148 #endif
149 #ifdef SIGCONT
150 {SIGCONT, "SIGCONT"},
151 #endif
152 #if defined(SIGEMT) && (!defined(SIGXCPU) || (SIGEMT != SIGXCPU))
153 {SIGEMT, "SIGEMT"},
154 #endif
155 #ifdef SIGFPE
156 {SIGFPE, "SIGFPE"},
157 #endif
158 #ifdef SIGHUP
159 {SIGHUP, "SIGHUP"},
160 #endif
161 #ifdef SIGILL
162 {SIGILL, "SIGILL"},
163 #endif
164 #ifdef SIGINT
165 {SIGINT, "SIGINT"},
166 #endif
167 #ifdef SIGIO
168 {SIGIO, "SIGIO"},
169 #endif
170 #if defined(SIGIOT) && (!defined(SIGABRT) || (SIGIOT != SIGABRT))
171 {SIGIOT, "SIGIOT"},
172 #endif
173 #ifdef SIGKILL
174 {SIGKILL, "SIGKILL"},
175 #endif
176 #if defined(SIGLOST) && (!defined(SIGIOT) || (SIGLOST != SIGIOT)) && (!defined(SIGURG) || (SIGLOST != SIGURG))
177 {SIGLOST, "SIGLOST"},
178 #endif
179 #ifdef SIGPIPE
180 {SIGPIPE, "SIGPIPE"},
181 #endif
182 #if defined(SIGPOLL) && (!defined(SIGIO) || (SIGPOLL != SIGIO))
183 {SIGPOLL, "SIGPOLL"},
184 #endif
185 #ifdef SIGPROF
186 {SIGPROF, "SIGPROF"},
187 #endif
188 #if defined(SIGPWR) && (!defined(SIGXFSZ) || (SIGPWR != SIGXFSZ))
189 {SIGPWR, "SIGPWR"},
190 #endif
191 #ifdef SIGQUIT
192 {SIGQUIT, "SIGQUIT"},
193 #endif
194 #ifdef SIGSEGV
195 {SIGSEGV, "SIGSEGV"},
196 #endif
197 #ifdef SIGSTOP
198 {SIGSTOP, "SIGSTOP"},
199 #endif
200 #ifdef SIGSYS
201 {SIGSYS, "SIGSYS"},
202 #endif
203 #ifdef SIGTERM
204 {SIGTERM, "SIGTERM"},
205 #endif
206 #ifdef SIGTRAP
207 {SIGTRAP, "SIGTRAP"},
208 #endif
209 #ifdef SIGTSTP
210 {SIGTSTP, "SIGTSTP"},
211 #endif
212 #ifdef SIGTTIN
213 {SIGTTIN, "SIGTTIN"},
214 #endif
215 #ifdef SIGTTOU
216 {SIGTTOU, "SIGTTOU"},
217 #endif
218 #if defined(SIGURG) && (!defined(SIGIO) || (SIGURG != SIGIO))
219 {SIGURG, "SIGURG"},
220 #endif
221 #if defined(SIGUSR1) && (!defined(SIGIO) || (SIGUSR1 != SIGIO))
222 {SIGUSR1, "SIGUSR1"},
223 #endif
224 #if defined(SIGUSR2) && (!defined(SIGURG) || (SIGUSR2 != SIGURG))
225 {SIGUSR2, "SIGUSR2"},
226 #endif
227 #ifdef SIGVTALRM
228 {SIGVTALRM, "SIGVTALRM"},
229 #endif
230 #ifdef SIGWINCH
231 {SIGWINCH, "SIGWINCH"},
232 #endif
233 #ifdef SIGXCPU
234 {SIGXCPU, "SIGXCPU"},
235 #endif
236 #ifdef SIGXFSZ
237 {SIGXFSZ, "SIGXFSZ"},
238 #endif
239 {-1, "unknown signal"},
240 };
241
242 /*
243 * Sink buffer:
244 * ____________________
245 * | | "size" current allocated length of buffer.
246 * | |
247 * |--------------------| "fill" fill point (# characters in buffer).
248 * | Raw |
249 * |--------------------| "mark" Marks end of cooked characters.
250 * | |
251 * | Cooked |
252 * | |
253 * | |
254 * |--------------------| "lastMark" Mark end of processed characters.
255 * | |
256 * | |
257 * | Processed |
258 * | |
259 * |____________________| 0
260 */
261 typedef struct {
262 char *name; /* Name of the sink */
263
264 char *doneVar; /* Name of a Tcl variable (malloc'ed)
265 * set to the collected data of the
266 * last UNIX subprocess. */
267
268 char *updateVar; /* Name of a Tcl variable (malloc'ed)
269 * updated as data is read from the
270 * pipe. */
271
272 char **updateCmd; /* Start of a Tcl command executed
273 * whenever data is read from the
274 * pipe. */
275
276 #if (TCL_MAJOR_VERSION >= 8)
277 Tcl_Obj **objv; /* */
278 int objc; /* */
279 #endif
280
281 int flags;
282
283 Tcl_File file; /* Used for backward compatability
284 * with Tcl 7.5 */
285 Tcl_Encoding encoding;
286 int fd; /* File descriptor of the pipe. */
287 int status;
288
289 int echo; /* Indicates if the pipeline's stderr stream
290 * should be echoed */
291 unsigned char *byteArr; /* Stores pipeline output (malloc-ed):
292 * Initially points to static storage
293 */
294 size_t size; /* Size of dynamically allocated buffer. */
295
296 size_t fill; /* # of bytes read into the buffer. Marks
297 * the current fill point of the buffer. */
298
299 size_t mark; /* # of bytes translated (cooked). */
300 size_t lastMark; /* # of bytes as of the last read.
301 * This indicates the start of the new
302 * data in the buffer since the last
303 * time the "update" variable was
304 * set. */
305
306 char *command; /* Command callback. */
307 unsigned char staticSpace[DEF_BUFFER_SIZE]; /* Static space */
308
309 } Sink;
310
311 #define SINK_BUFFERED (1<<0)
312 #define SINK_KEEP_NL (1<<1)
313 #define SINK_NOTIFY (1<<2)
314
315 typedef struct {
316 char *statVar; /* Name of a Tcl variable set to the
317 * exit status of the last
318 * process. Setting this variable
319 * triggers the termination of all
320 * subprocesses (regardless whether
321 * they have already completed) */
322
323 int signalNum; /* If non-zero, indicates the signal
324 * to send subprocesses when cleaning
325 * up.*/
326 int localVars; /* Use local vars. */
327 int keepNewline; /* If non-zero, indicates to set Tcl
328 * output variables with trailing
329 * newlines intact */
330
331 int lineBuffered; /* If non-zero, indicates provide data
332 * to update variable and update proc on
333 * a line-by-line basis. */
334
335 int interval; /* Interval to poll for the exiting
336 * processes */
337 char *outputEncodingName; /* Name of decoding scheme to use when
338 * translating output data. */
339 char *errorEncodingName; /* Name of decoding scheme to use when
340 * translating output data. */
341
342 /* Private */
343 Tcl_Interp *interp; /* Interpreter containing variables */
344
345 int nProcs; /* Number of processes in pipeline */
346 Process *procArr; /* Array of process tokens from pipeline.
347 * The token for Unix are pid_t, while
348 * for Win32 they're handles. */
349
350 int traced; /* Indicates that the status variable
351 * is currently being traced. */
352 int detached; /* Indicates that the pipeline is
353 * detached from standard I/O, running
354 * in the background. */
355 int nTimers; /* Number of timer handlers */
356 Tcl_TimerToken *timerTokens;/* Array of tokens for timer handlers which
357 * polls for the exit status of each
358 * sub-process. If zero, there's no
359 * timer handler queued. */
360
361 int *exitCodePtr; /* Pointer to a memory location to
362 * contain the last process' exit
363 * code. */
364 int *donePtr;
365
366 Sink sink1, sink2;
367 int maxBytes; /* Max string length. */
368 int maxExceed;
369 int varFlags;
370 int doRaise;
371 int closeKill;
372 int cKilled;
373 } BackgroundInfo;
374
375
376 static Blt_SwitchParseProc StringToSignal;
377 static Blt_SwitchCustom killSignalSwitch =
378 {
379 StringToSignal, (Blt_SwitchFreeProc *)NULL, (ClientData)0,
380 };
381
382 static Blt_SwitchSpec switchSpecs[] =
383 {
384 {BLT_SWITCH_INT, "-check",
385 Blt_Offset(BackgroundInfo, interval), 0},
386 {BLT_SWITCH_INT, "-closeonkill",
387 Blt_Offset(BackgroundInfo, closeKill), 0},
388 {BLT_SWITCH_STRING, "-command",
389 Blt_Offset(BackgroundInfo, sink1.command), 0},
390 {BLT_SWITCH_STRING, "-decodeerror",
391 Blt_Offset(BackgroundInfo, errorEncodingName), 0},
392 {BLT_SWITCH_STRING, "-decodeoutput",
393 Blt_Offset(BackgroundInfo, outputEncodingName), 0},
394 {BLT_SWITCH_BOOLEAN, "-echo",
395 Blt_Offset(BackgroundInfo, sink2.echo), 0},
396 {BLT_SWITCH_STRING, "-error",
397 Blt_Offset(BackgroundInfo, sink2.doneVar), 0},
398 {BLT_SWITCH_BOOLEAN, "-keepnewline",
399 Blt_Offset(BackgroundInfo, keepNewline), 0},
400 {BLT_SWITCH_CUSTOM, "-killsignal",
401 Blt_Offset(BackgroundInfo, signalNum), 0, &killSignalSwitch},
402 {BLT_SWITCH_STRING, "-lasterror",
403 Blt_Offset(BackgroundInfo, sink2.updateVar), 0},
404 {BLT_SWITCH_STRING, "-lastoutput",
405 Blt_Offset(BackgroundInfo, sink1.updateVar), 0},
406 {BLT_SWITCH_INT, "-limit",
407 Blt_Offset(BackgroundInfo, maxBytes), 0},
408 {BLT_SWITCH_BOOLEAN, "-linebuffered",
409 Blt_Offset(BackgroundInfo, lineBuffered), 0},
410 {BLT_SWITCH_BOOLEAN, "-local",
411 Blt_Offset(BackgroundInfo, localVars), 0},
412 {BLT_SWITCH_LIST, "-onerror",
413 Blt_Offset(BackgroundInfo, sink2.updateCmd), 0},
414 {BLT_SWITCH_LIST, "-onoutput",
415 Blt_Offset(BackgroundInfo, sink1.updateCmd), 0},
416 {BLT_SWITCH_STRING, "-output",
417 Blt_Offset(BackgroundInfo, sink1.doneVar), 0},
418 {BLT_SWITCH_BOOLEAN, "-raise",
419 Blt_Offset(BackgroundInfo, doRaise), 0},
420 /* {BLT_SWITCH_STRING, "-update",
421 Blt_Offset(BackgroundInfo, sink1.updateVar), 0},*/
422 {BLT_SWITCH_END, NULL, 0, 0}
423 };
424
425 static char *VariableProc _ANSI_ARGS_((ClientData clientData,
426 Tcl_Interp *interp, char *part1, char *part2, int flags));
427 static void TimerProc _ANSI_ARGS_((ClientData clientData));
428 static void StdoutProc _ANSI_ARGS_((ClientData clientData, int mask));
429 static void StderrProc _ANSI_ARGS_((ClientData clientData, int mask));
430 static void AddTimerHandler _ANSI_ARGS_((BackgroundInfo *bgPtr,int interval));
431 static void InterpDeleted _ANSI_ARGS_(( ClientData clientData, Tcl_Interp *interp));
432
433 /*
434 *----------------------------------------------------------------------
435 *
436 * GetSignal --
437 *
438 * Convert a string represent a signal number into its integer
439 * value.
440 *
441 * Results:
442 * The return value is a standard Tcl result.
443 *
444 *----------------------------------------------------------------------
445 */
446 /*ARGSUSED*/
447 static int
448 StringToSignal(clientData, interp, switchName, string, record, offset)
449 ClientData clientData; /* Contains a pointer to the tabset containing
450 * this image. */
451 Tcl_Interp *interp; /* Interpreter to send results back to */
452 char *switchName; /* Not used. */
453 char *string; /* String representation */
454 char *record; /* Structure record */
455 int offset; /* Offset to field in structure */
456 {
457 int *signalPtr = (int *)(record + offset);
458 int signalNum;
459
460 if ((string == NULL) || (*string == '\0')) {
461 *signalPtr = 0;
462 return TCL_OK;
463 }
464 if (isdigit(UCHAR(string[0]))) {
465 if (Tcl_GetInt(interp, string, &signalNum) != TCL_OK) {
466 return TCL_ERROR;
467 }
468 } else {
469 char *name;
470 register SignalId *sigPtr;
471
472 name = string;
473
474 /* Clip off any "SIG" prefix from the signal name */
475 if ((name[0] == 'S') && (name[1] == 'I') && (name[2] == 'G')) {
476 name += 3;
477 }
478 signalNum = -1;
479 for (sigPtr = signalIds; sigPtr->number > 0; sigPtr++) {
480 if (strcmp(sigPtr->name + 3, name) == 0) {
481 signalNum = sigPtr->number;
482 break;
483 }
484 }
485 if (signalNum < 0) {
486 Tcl_AppendResult(interp, "unknown signal \"", string, "\"",
487 (char *)NULL);
488 return TCL_ERROR;
489 }
490 }
491 if ((signalNum < 0) || (signalNum > NSIG)) {
492 /* Outside range of signals */
493 Tcl_AppendResult(interp, "signal number \"", string,
494 "\" is out of range", (char *)NULL);
495 return TCL_ERROR;
496 }
497 *signalPtr = signalNum;
498 return TCL_OK;
499 }
500
501
502 /*
503 *----------------------------------------------------------------------
504 *
505 * GetSinkData --
506 *
507 * Returns the data currently saved in the buffer
508 *
509 *----------------------------------------------------------------------
510 */
511 static void
512 GetSinkData(sinkPtr, dataPtr, lengthPtr)
513 Sink *sinkPtr;
514 unsigned char **dataPtr;
515 size_t *lengthPtr;
516 {
517 size_t length;
518
519 sinkPtr->byteArr[sinkPtr->mark] = '\0';
520 length = sinkPtr->mark;
521 if ((sinkPtr->mark > 0) && (sinkPtr->encoding != ENCODING_BINARY)) {
522 unsigned char *last;
523
524 last = sinkPtr->byteArr + (sinkPtr->mark - 1);
525 if ((!(sinkPtr->flags & SINK_KEEP_NL)) && (*last == '\n')) {
526 length--;
527 }
528 }
529 *dataPtr = sinkPtr->byteArr;
530 *lengthPtr = length;
531 }
532
533 /*
534 *----------------------------------------------------------------------
535 *
536 * NextBlock --
537 *
538 * Returns the next block of data since the last time this
539 * routine was called.
540 *
541 *----------------------------------------------------------------------
542 */
543 static unsigned char *
544 NextBlock(sinkPtr, lengthPtr)
545 Sink *sinkPtr;
546 int *lengthPtr;
547 {
548 unsigned char *string;
549 int length;
550
551 string = sinkPtr->byteArr + sinkPtr->lastMark;
552 length = sinkPtr->mark - sinkPtr->lastMark;
553 sinkPtr->lastMark = sinkPtr->mark;
554 if (length > 0) {
555 if ((!(sinkPtr->flags & SINK_KEEP_NL)) &&
556 (string[length - 1] == '\n')) {
557 length--;
558 }
559 *lengthPtr = length;
560 return string;
561 }
•562 *lengthPtr = length;
563 return NULL;
564 }
565
566 /*
567 *----------------------------------------------------------------------
568 *
569 * NextLine --
570 *
571 * Returns the next line of data.
572 *
573 *----------------------------------------------------------------------
574 */
575 static unsigned char *
576 NextLine(sinkPtr, lengthPtr)
577 Sink *sinkPtr;
578 int *lengthPtr;
579 {
580 if (sinkPtr->mark > sinkPtr->lastMark) {
581 unsigned char *string;
582 int newBytes;
583 register int i;
584
585 string = sinkPtr->byteArr + sinkPtr->lastMark;
586 newBytes = sinkPtr->mark - sinkPtr->lastMark;
587 for (i = 0; i < newBytes; i++) {
588 if (string[i] == '\n') {
589 int length;
590
591 length = i + 1;
592 sinkPtr->lastMark += length;
593 if (!(sinkPtr->flags & SINK_KEEP_NL)) {
594 length--; /* Backup over the newline. */
595 }
596 *lengthPtr = length;
597 return string;
598 }
599 }
600 /* Newline not found. On errors or EOF, also return a partial line. */
601 if (sinkPtr->status < 0) {
602 *lengthPtr = newBytes;
603 sinkPtr->lastMark = sinkPtr->mark;
604 return string;
605 }
606 }
•607 *lengthPtr = 0;
608 return NULL;
609 }
610 /*
611 *----------------------------------------------------------------------
612 *
613 * ResetSink --
614 *
615 * Removes the bytes already processed from the buffer, possibly
616 * resetting it to empty. This used when we don't care about
617 * keeping all the data collected from the channel (no -output
618 * flag and the process is detached).
619 *
620 *----------------------------------------------------------------------
621 */
622 static void
623 ResetSink(sinkPtr)
624 Sink *sinkPtr;
625 {
626 if ((sinkPtr->flags & SINK_BUFFERED) &&
627 (sinkPtr->fill > sinkPtr->lastMark)) {
628 register size_t i, j;
629
630 /* There may be bytes remaining in the buffer, awaiting
631 * another read before we see the next newline. So move the
632 * bytes to the front of the array. */
633
634 for (i = 0, j = sinkPtr->lastMark; j < sinkPtr->fill; i++, j++) {
635 sinkPtr->byteArr[i] = sinkPtr->byteArr[j];
636 }
637 /* Move back the fill point and processed point. */
638 sinkPtr->fill -= sinkPtr->lastMark;
639 sinkPtr->mark -= sinkPtr->lastMark;
640 } else {
641 sinkPtr->mark = sinkPtr->fill = 0;
642 }
643 sinkPtr->lastMark = 0;
644 }
645
646 /*
647 *----------------------------------------------------------------------
648 *
649 * InitSink --
650 *
651 * Initializes the buffer's storage.
652 *
653 * Results:
654 * None.
655 *
656 * Side effects:
657 * Storage is cleared.
658 *
659 *----------------------------------------------------------------------
660 */
661 static void
662 InitSink(bgPtr, sinkPtr, name, encoding)
663 BackgroundInfo *bgPtr;
664 Sink *sinkPtr;
665 char *name;
666 Tcl_Encoding encoding;
667 {
668 sinkPtr->name = name;
669 sinkPtr->echo = FALSE;
670 sinkPtr->fd = -1;
•671 sinkPtr->file = (Tcl_File)0;
672 sinkPtr->byteArr = sinkPtr->staticSpace;
673 sinkPtr->size = DEF_BUFFER_SIZE;
674 sinkPtr->encoding = encoding;
675 if (bgPtr->keepNewline) {
676 sinkPtr->flags |= SINK_KEEP_NL;
677 }
678 if (bgPtr->lineBuffered) {
679 sinkPtr->flags |= SINK_BUFFERED;
680 }
681 if ((sinkPtr->updateCmd != NULL) ||
682 (sinkPtr->updateVar != NULL) ||
683 (sinkPtr->echo)) {
684 sinkPtr->flags |= SINK_NOTIFY;
685 }
686 #if (TCL_MAJOR_VERSION >= 8)
687 if (sinkPtr->updateCmd != NULL) {
688 Tcl_Obj **objArr;
689 char **p;
690 int count;
691 register int i;
692
693 count = 0;
694 for (p = sinkPtr->updateCmd; *p != NULL; p++) {
695 count++;
696 }
697 objArr = Blt_Malloc((count + 1) * sizeof(Tcl_Obj *));
698 for (i = 0; i < count; i++) {
699 objArr[i] = Tcl_NewStringObj(sinkPtr->updateCmd[i], -1);
700 Tcl_IncrRefCount(objArr[i]);
701 }
702 sinkPtr->objv = objArr;
703 sinkPtr->objc = count + 1;
704 }
705 #endif
706 ResetSink(sinkPtr);
707 }
708
709 /*
710 *----------------------------------------------------------------------
711 *
712 * FreeSinkBuffer --
713 *
714 * Frees the buffer's storage, freeing any malloc'ed space.
715 *
716 * Results:
717 * None.
718 *
719 *----------------------------------------------------------------------
720 */
721 static void
722 FreeSinkBuffer(sinkPtr)
723 Sink *sinkPtr;
724 {
725 if (sinkPtr->byteArr != sinkPtr->staticSpace) {
726 Blt_Free(sinkPtr->byteArr);
727 }
728 sinkPtr->fd = -1;
•729 sinkPtr->file = (Tcl_File)0;
730 #if (TCL_MAJOR_VERSION >= 8)
731 if (sinkPtr->objv != NULL) {
732 register int i;
733
734 for (i = 0; i < sinkPtr->objc - 1; i++) {
735 Tcl_DecrRefCount(sinkPtr->objv[i]);
736 }
737 Blt_Free(sinkPtr->objv);
738 }
739 #endif
740 }
741
742
743 /*
744 *----------------------------------------------------------------------
745 *
746 * ExtendSinkBuffer --
747 *
748 * Doubles the size of the current buffer.
749 *
750 * Results:
751 * None.
752 *
753 *----------------------------------------------------------------------
754 */
755 static int
756 ExtendSinkBuffer(sinkPtr)
757 Sink *sinkPtr;
758 {
759 unsigned char *arrayPtr;
760 register unsigned char *srcPtr, *destPtr, *endPtr;
761 /*
762 * Allocate a new array, double the old size
763 */
764 sinkPtr->size += sinkPtr->size;
765 arrayPtr = Blt_Malloc(sizeof(unsigned char) * sinkPtr->size);
766 if (arrayPtr == NULL) {
767 return -1;
768 }
769 srcPtr = sinkPtr->byteArr;
770 endPtr = sinkPtr->byteArr + sinkPtr->fill;
771 destPtr = arrayPtr;
772 while (srcPtr < endPtr) {
773 *destPtr++ = *srcPtr++;
774 }
775 if (sinkPtr->byteArr != sinkPtr->staticSpace) {
776 Blt_Free(sinkPtr->byteArr);
777 }
778 sinkPtr->byteArr = arrayPtr;
779
780 return (sinkPtr->size - sinkPtr->fill); /* Return bytes left. */
781 }
782
783 /*
784 *----------------------------------------------------------------------
785 *
786 * ReadBytes --
787 *
788 * Reads and appends any available data from a given file descriptor
789 * to the buffer.
790 *
791 * Results:
792 * Returns TCL_OK when EOF is found, TCL_RETURN if reading
793 * data would block, and TCL_ERROR if an error occurred.
794 *
795 *----------------------------------------------------------------------
796 */
797 static void
798 ReadBytes(bgPtr, sinkPtr)
799 BackgroundInfo *bgPtr;
800 Sink *sinkPtr;
801 {
802 int nBytes, bytesLeft;
803 register int i;
804 unsigned char *array;
805
806 /*
807 * ------------------------------------------------------------------
808 *
809 * Worry about indefinite postponement.
810 *
811 * Typically we want to stay in the read loop as long as it takes
812 * to collect all the data that's currently available. But if
813 * it's coming in at a constant high rate, we need to arbitrarily
814 * break out at some point. This allows for both setting the
815 * update variable and the Tk program to handle idle events.
816 *
817 * ------------------------------------------------------------------
818 */
819
820 for (i = 0; i < MAX_READS; i++) {
821
822 /* Allocate a larger buffer when the number of remaining bytes
823 * is below the threshold BLOCK_SIZE. */
824
825 bytesLeft = sinkPtr->size - sinkPtr->fill;
826
827 if (bytesLeft < BLOCK_SIZE) {
828 bytesLeft = ExtendSinkBuffer(sinkPtr);
829 if (bytesLeft < 0) {
830 sinkPtr->status = READ_ERROR;
831 return;
832 }
833 }
834 array = sinkPtr->byteArr + sinkPtr->fill;
835
836 /*
837 * Read into a buffer but make sure we leave room for a
838 * trailing NUL byte.
839 */
840 nBytes = read(sinkPtr->fd, array, bytesLeft - 1);
841 if (nBytes == 0) { /* EOF: break out of loop. */
842 sinkPtr->status = READ_EOF;
843 return;
844 }
845 if (nBytes < 0) {
846 #ifdef O_NONBLOCK
847 #define BLOCKED EAGAIN
848 #else
849 #define BLOCKED EWOULDBLOCK
850 #endif /*O_NONBLOCK*/
851 /* Either an error has occurred or no more data is
852 * currently available to read. */
853 if (errno == BLOCKED) {
854 sinkPtr->status = READ_AGAIN;
855 return;
856 }
857 sinkPtr->byteArr[0] = '\0';
858 sinkPtr->status = READ_ERROR;
859 return;
860 }
861 sinkPtr->fill += nBytes;
862 sinkPtr->byteArr[sinkPtr->fill] = '\0';
863 }
864 sinkPtr->status = nBytes;
865 }
866
867 #define IsOpenSink(sinkPtr) ((sinkPtr)->fd != -1)
868
869 static void
870 CloseSink(bgPtr, interp, sinkPtr)
871 BackgroundInfo *bgPtr;
872 Tcl_Interp *interp;
873 Sink *sinkPtr;
874 {
875 unsigned char *data = NULL;
876 size_t length;
877
878 if (IsOpenSink(sinkPtr)) {
879 close(sinkPtr->fd);
880 #ifdef FILEHANDLER_USES_TCLFILES
881 Tcl_DeleteFileHandler(sinkPtr->file);
882 Tcl_FreeFile(sinkPtr->file);
883 #else
884 Tcl_DeleteFileHandler(sinkPtr->fd);
885 #endif
•886 sinkPtr->file = (Tcl_File)0;
887 sinkPtr->fd = -1;
888
889 #if WINDEBUG
890 PurifyPrintf("CloseSink: set done var %s\n", sinkPtr->name);
891 #endif
892 if (sinkPtr->doneVar != NULL && !Tcl_InterpDeleted(interp)) {
893 /*
894 * If data is to be collected, set the "done" variable
895 * with the contents of the buffer.
896 */
897 GetSinkData(sinkPtr, &data, &length);
898 #if (TCL_VERSION_NUMBER < _VERSION(8,1,0))
899 data[length] = '\0';
900 if (Tcl_SetVar(interp, sinkPtr->doneVar, data,
901 bgPtr->varFlags) == NULL) {
902 Tcl_BackgroundError(interp);
903 }
904 #else
905 if (Tcl_SetVar2Ex(interp, sinkPtr->doneVar, NULL,
906 Tcl_NewByteArrayObj(data, length),
907 (bgPtr->varFlags | TCL_LEAVE_ERR_MSG)) == NULL) {
908 Tcl_BackgroundError(interp);
909 }
910 #endif
911 }
912 #if WINDEBUG
913 PurifyPrintf("CloseSink %s: done\n", sinkPtr->name);
914 #endif
915 }
916 }
917
918 static void
919 SinkCallback(interp, sinkPtr, status)
920 Tcl_Interp *interp;
921 Sink *sinkPtr;
922 char *status;
923 {
924 unsigned char *data = NULL;
925 size_t length;
926 if (sinkPtr->command != NULL && !Tcl_InterpDeleted(interp)) {
927 Tcl_DString dStr;
928 Tcl_DStringInit(&dStr);
929 GetSinkData(sinkPtr, &data, &length);
930 Tcl_DStringAppend(&dStr, sinkPtr->command, -1);
•931 Tcl_DStringAppendElement(&dStr, (char *)data);
932 Tcl_DStringAppendElement(&dStr, status);
933 if (Tcl_GlobalEval(interp, Tcl_DStringValue(&dStr)) != TCL_OK) {
934 Tcl_BackgroundError(interp);
935 }
936 Tcl_DStringFree(&dStr);
937 }
938 }
939 /*
940 *----------------------------------------------------------------------
941 *
942 * CookSink --
943 *
944 * For Windows, translate CR/NL combinations to NL alone.
945 *
946 * Results:
947 * None.
948 *
949 * Side Effects:
950 * The size of the byte array may shrink and array contents
951 * shifted as carriage returns are found and removed.
952 *
953 *----------------------------------------------------------------------
954 */
955 static void
956 CookSink(interp, sinkPtr)
957 Tcl_Interp *interp;
958 Sink *sinkPtr;
959 {
960 unsigned char *srcPtr, *endPtr;
961 #ifdef WIN32
962 size_t oldMark;
963
964 oldMark = sinkPtr->mark;
965 #endif
966 if (sinkPtr->encoding == ENCODING_BINARY) { /* binary */
967 /* No translation needed. */
968 sinkPtr->mark = sinkPtr->fill;
969 } else if (sinkPtr->encoding == ENCODING_ASCII) { /* ascii */
970 #if (TCL_VERSION_NUMBER < _VERSION(8,1,0))
971 /* Convert NUL bytes to question marks. */
972 srcPtr = sinkPtr->byteArr + sinkPtr->mark;
973 endPtr = sinkPtr->byteArr + sinkPtr->fill;
974 while (srcPtr < endPtr) {
975 if (*srcPtr == '\0') {
976 *srcPtr = '?';
977 }
978 srcPtr++;
979 }
980 #endif /* < 8.1.0 */
981 /* One-to-one translation. mark == fill. */
982 sinkPtr->mark = sinkPtr->fill;
983 #if (TCL_VERSION_NUMBER >= _VERSION(8,1,0))
984 } else { /* unicode. */
985 int nSrcCooked, nCooked;
986 int result;
987 size_t cookedSize, spaceLeft, needed;
988 size_t nRaw, nLeftOver;
989 unsigned char *destPtr;
990 unsigned char *raw, *cooked;
991 unsigned char leftover[100];
992
993 raw = sinkPtr->byteArr + sinkPtr->mark;
994 nRaw = sinkPtr->fill - sinkPtr->mark;
995 /* Ideally, the cooked buffer size should be smaller */
996 cookedSize = nRaw * TCL_UTF_MAX + 1;
997 cooked = Blt_Malloc(cookedSize);
998 result = Tcl_ExternalToUtf(interp, sinkPtr->encoding,
999 (char *)raw, nRaw, 0, NULL, (char *)cooked,
1000 cookedSize, &nSrcCooked, &nCooked, NULL);
1001 nLeftOver = 0;
1002 if (result == TCL_CONVERT_MULTIBYTE) {
1003 /*
1004 * Last multibyte sequence wasn't completed. Save the
1005 * extra characters in a temporary buffer.
1006 */
1007 nLeftOver = (nRaw - nSrcCooked);
1008 srcPtr = sinkPtr->byteArr + (sinkPtr->mark + nSrcCooked);
1009 endPtr = srcPtr + nLeftOver;
1010 destPtr = leftover;
1011 while (srcPtr < endPtr) {
1012 *destPtr++ = *srcPtr++;
1013 }
1014 }
1015 /*
1016 * Create a bigger
1017 */
1018
1019 needed = nLeftOver + nCooked;
1020 spaceLeft = sinkPtr->size - sinkPtr->mark;
1021 if (spaceLeft >= needed) {
1022 spaceLeft = ExtendSinkBuffer(sinkPtr);
1023 }
1024 assert(spaceLeft > needed);
1025 /*
1026 * Replace the characters from the mark with the translated
1027 * characters.
1028 */
1029 srcPtr = cooked;
1030 endPtr = cooked + nCooked;
1031 destPtr = sinkPtr->byteArr + sinkPtr->mark;
1032 while (srcPtr < endPtr) {
1033 *destPtr++ = *srcPtr++;
1034 }
1035 /* Add the number of newly translated characters to the mark */
1036 sinkPtr->mark += nCooked;
1037
1038 srcPtr = leftover;
1039 endPtr = leftover + nLeftOver;
1040 while (srcPtr < endPtr) {
1041 *destPtr++ = *srcPtr++;
1042 }
1043 sinkPtr->fill = sinkPtr->mark + nLeftOver;
1044 #endif /* >= 8.1.0 */
1045 }
1046 #ifdef WIN32
1047 /*
1048 * Translate CRLF character sequences to LF characters. We have to
1049 * do this after converting the string to UTF from UNICODE.
1050 */
1051 if (sinkPtr->encoding != ENCODING_BINARY) {
1052 int count;
1053 unsigned char *destPtr;
1054
1055 destPtr = srcPtr = sinkPtr->byteArr + oldMark;
1056 endPtr = sinkPtr->byteArr + sinkPtr->fill;
1057 *endPtr = '\0';
1058 count = 0;
1059 for (endPtr--; srcPtr < endPtr; srcPtr++) {
1060 if ((*srcPtr == '\r') && (*(srcPtr + 1) == '\n')) {
1061 count++;
1062 continue; /* Skip the CR in CR/LF sequences. */
1063 }
1064 if (srcPtr != destPtr) {
1065 *destPtr = *srcPtr; /* Collapse the string, overwriting
1066 * the \r's encountered. */
1067 }
1068 destPtr++;
1069 }
1070 sinkPtr->mark -= count;
1071 sinkPtr->fill -= count;
1072 *destPtr = *srcPtr; /* Copy the last byte */
1073 if (*destPtr == '\r') {
1074 sinkPtr->mark--;
1075 }
1076 }
1077 #endif /* WIN32 */
1078 }
1079
1080 #ifdef WIN32
1081 /*
1082 *----------------------------------------------------------------------
1083 *
1084 * WaitProcess --
1085 *
1086 * Emulates the waitpid system call under the Win32 API.
1087 *
1088 * Results:
1089 * Returns 0 if the process is still alive, -1 on an error, or
1090 * the pid on a clean close.
1091 *
1092 * Side effects:
1093 * Unless WNOHANG is set and the wait times out, the process
1094 * information record will be deleted and the process handle
1095 * will be closed.
1096 *
1097 *----------------------------------------------------------------------
1098 */
1099 #define WINDEBUG 0
1100 static int
1101 WaitProcess(
1102 Process child,
1103 int *statusPtr,
1104 int flags)
1105 {
1106 int result;
1107 DWORD status, exitCode;
1108 int timeout;
1109
1110 #if WINDEBUG
1111 PurifyPrintf("WAITPID(%x)\n", child.hProcess);
1112 #endif
1113 *statusPtr = 0;
1114 if (child.hProcess == INVALID_HANDLE_VALUE) {
1115 errno = EINVAL;
1116 return -1;
1117 }
1118 #if WINDEBUG
1119 PurifyPrintf("WAITPID: waiting for 0x%x\n", child.hProcess);
1120 #endif
1121 timeout = (flags & WNOHANG) ? 0 : INFINITE;
1122 status = WaitForSingleObject(child.hProcess, timeout);
1123
1124 #if WINDEBUG
1125 PurifyPrintf("WAITPID: wait status is %d\n", status);
1126 #endif
1127 switch (status) {
1128 case WAIT_FAILED:
1129 errno = ECHILD;
1130 *statusPtr = ECHILD;
1131 result = -1;
1132 break;
1133
1134 case WAIT_TIMEOUT:
1135 if (timeout == 0) {
1136 return 0; /* Try again */
1137 }
1138 result = 0;
1139 break;
1140
1141 default:
1142 case WAIT_ABANDONED:
1143 case WAIT_OBJECT_0:
1144 GetExitCodeProcess(child.hProcess, &exitCode);
1145 *statusPtr = ((exitCode << 8) & 0xff00);
1146 #if WINDEBUG
1147 PurifyPrintf("WAITPID: exit code of %d is %d (%x)\n", child.hProcess,
1148 *statusPtr, exitCode);
1149 #endif
1150 result = child.pid;
1151 assert(result != -1);
1152 break;
1153 }
1154 CloseHandle(child.hProcess);
1155 return result;
1156 }
1157
1158 static BOOL CALLBACK
1159 EnumWindowsProc(HWND hWnd, LPARAM lParam)
1160 {
1161 DWORD pid = 0;
1162 Process *procPtr = (Process *)lParam;
1163
1164 GetWindowThreadProcessId(hWnd, &pid);
1165 if (pid == procPtr->pid) {
1166 PostMessage(hWnd, WM_CLOSE, 0, 0);
1167 }
1168 return TRUE;
1169 }
1170
1171 /*
1172 *----------------------------------------------------------------------
1173 *
1174 * KillProcess --
1175 *
1176 * Emulates the UNIX kill system call under Win32 API.
1177 *
1178 * Results:
1179 * Returns 0 if the process is killed, -1 on an error.
1180 *
1181 * Side effects:
1182 * Process is terminated.
1183 *
1184 *----------------------------------------------------------------------
1185 */
1186 static int
1187 KillProcess(Process proc, int signal)
1188 {
1189 DWORD status;
1190
1191 if ((proc.hProcess == NULL) || (proc.hProcess == INVALID_HANDLE_VALUE)) {
1192 errno = EINVAL;
1193 return -1;
1194 }
1195
1196 EnumWindows(EnumWindowsProc, (LPARAM)&proc);
1197
1198 /*
1199 * Wait on the handle. If it signals, great. If it times out,
1200 * then call TerminateProcess on it.
1201 *
1202 * On Windows 95/98 this also has the added benefit of stopping
1203 * KERNEL32.dll from dumping. The 2 second number is arbitrary.
1204 * (1 second seems to fail intermittently).
1205 */
1206 status = WaitForSingleObject(proc.hProcess, 2000);
1207 if (status == WAIT_OBJECT_0) {
1208 return 0;
1209 }
1210 if (!TerminateProcess(proc.hProcess, 1)) {
1211 #if WINDEBUG
1212 PurifyPrintf("can't terminate process (handle=%d): %s\n",
1213 proc.hProcess, Blt_LastError());
1214 #endif /* WINDEBUG */
1215 return -1;
1216 }
1217 return 0;
1218 }
1219
1220 #endif /* WIN32 */
1221
1222 #if (TCL_VERSION_NUMBER < _VERSION(8,1,0))
1223
1224 static void
1225 NotifyOnUpdate(bgPtr, interp, sinkPtr, data, nBytes)
1226 BackgroundInfo *bgPtr;
1227 Tcl_Interp *interp;
1228 Sink *sinkPtr;
1229 unsigned char *data;
1230 int nBytes;
1231 {
1232 char save;
1233
1234 #if WINDEBUG_0
1235 PurifyPrintf("read %s\n", data);
1236 #endif
1237 if (data[0] == '\0') {
1238 return;
1239 }
1240 save = data[nBytes];
1241 data[nBytes] = '\0';
1242 if (sinkPtr->echo) {
1243 Tcl_Channel channel;
1244
1245 channel = Tcl_GetStdChannel(TCL_STDERR);
1246 if (channel == NULL) {
1247 Tcl_AppendResult(interp, "can't get stderr channel", (char *)NULL);
1248 Tcl_BackgroundError(interp);
1249 sinkPtr->echo = FALSE;
1250 } else {
1251 Tcl_Write(channel, data, nBytes);
1252 if (save == '\n') {
1253 Tcl_Write(channel, "\n", 1);
1254 }
1255 Tcl_Flush(channel);
1256 }
1257 }
1258 if (sinkPtr->updateCmd != NULL) {
1259 Tcl_DString dString;
1260 int result;
1261 register char **p;
1262
1263 Tcl_DStringInit(&dString);
1264 for (p = sinkPtr->updateCmd; *p != NULL; p++) {
1265 Tcl_DStringAppendElement(&dString, *p);
1266 }
1267 Tcl_DStringAppendElement(&dString, data);
1268 result = Tcl_GlobalEval(interp, Tcl_DStringValue(&dString));
1269 Tcl_DStringFree(&dString);
1270 if (result != TCL_OK) {
1271 Tcl_BackgroundError(interp);
1272 }
1273 }
1274 if (sinkPtr->updateVar != NULL) {
1275 int flags;
1276 char *result;
1277
1278 flags = (bgPtr->varFlags | TCL_LEAVE_ERR_MSG);
1279 result = Tcl_SetVar(interp, sinkPtr->updateVar, data, flags);
1280 if (result == NULL) {
1281 Tcl_BackgroundError(interp);
1282 }
1283 }
1284 data[nBytes] = save;
1285 }
1286
1287 #else
1288
1289 static void
1290 NotifyOnUpdate(bgPtr, interp, sinkPtr, data, nBytes)
1291 BackgroundInfo *bgPtr;
1292 Tcl_Interp *interp;
1293 Sink *sinkPtr;
1294 unsigned char *data;
1295 int nBytes;
1296 {
1297 Tcl_Obj *objPtr;
1298
1299 #if WINDEBUG_0
1300 PurifyPrintf("read %s\n", data);
1301 #endif
1302 if ((nBytes == 0) || (data[0] == '\0')) {
1303 return;
1304 }
1305 if (sinkPtr->echo) {
1306 Tcl_Channel channel;
1307
1308 channel = Tcl_GetStdChannel(TCL_STDERR);
1309 if (channel == NULL) {
1310 Tcl_AppendResult(interp, "can't get stderr channel", (char *)NULL);
1311 Tcl_BackgroundError(interp);
1312 sinkPtr->echo = FALSE;
1313 } else {
1314 if (data[nBytes] == '\n') {
1315 objPtr = Tcl_NewByteArrayObj(data, nBytes + 1);
1316 } else {
1317 objPtr = Tcl_NewByteArrayObj(data, nBytes);
1318 }
1319 Tcl_WriteObj(channel, objPtr);
1320 Tcl_Flush(channel);
1321 }
1322 }
1323
1324 objPtr = Tcl_NewByteArrayObj(data, nBytes);
1325 Tcl_IncrRefCount(objPtr);
1326 if (sinkPtr->objv != NULL) {
1327 int result;
1328
1329 sinkPtr->objv[sinkPtr->objc - 1] = objPtr;
1330 result = Tcl_EvalObjv(interp, sinkPtr->objc, sinkPtr->objv, TCL_GLOBAL_ONLY);
1331 if (result != TCL_OK) {
1332 Tcl_BackgroundError(interp);
1333 }
1334 }
1335 if (sinkPtr->updateVar != NULL) {
1336 Tcl_Obj *result;
1337
1338 result = Tcl_SetVar2Ex(interp, sinkPtr->updateVar, NULL, objPtr,
1339 (bgPtr->varFlags | TCL_LEAVE_ERR_MSG));
1340 if (result == NULL) {
1341 Tcl_BackgroundError(interp);
1342 }
1343 }
1344 Tcl_DecrRefCount(objPtr);
1345 }
1346
1347 #endif /* < 8.1.0 */
1348
1349 static int
1350 CollectData(bgPtr, sinkPtr)
1351 BackgroundInfo *bgPtr;
1352 Sink *sinkPtr;
1353 {
1354 if ((bgPtr->detached) && (sinkPtr->doneVar == NULL) && (sinkPtr->command == NULL)) {
1355 ResetSink(sinkPtr);
1356 }
1357 ReadBytes(bgPtr, sinkPtr);
1358 CookSink(bgPtr->interp, sinkPtr);
1359 if ((sinkPtr->mark > sinkPtr->lastMark) &&
1360 (sinkPtr->flags & SINK_NOTIFY)) {
1361 unsigned char *data;
1362 int length;
1363
1364 if (sinkPtr->flags & SINK_BUFFERED) {
1365 /* For line-by-line updates, call NotifyOnUpdate for each
1366 * new complete line. */
1367 while ((data = NextLine(sinkPtr, &length)) != NULL) {
1368 NotifyOnUpdate(bgPtr, bgPtr->interp, sinkPtr, data, length);
1369 }
1370 } else {
1371 data = NextBlock(sinkPtr, &length);
1372 NotifyOnUpdate(bgPtr, bgPtr->interp, sinkPtr, data, length);
1373 }
1374 }
1375 if (bgPtr->maxBytes>0) {
1376 if (sinkPtr->mark >= bgPtr->maxBytes) {
1377 bgPtr->maxExceed = 1;
1378 return TCL_BREAK;
1379 }
1380 }
1381 if (sinkPtr->status >= 0) {
1382 return TCL_OK;
1383 }
1384 if (sinkPtr->status == READ_ERROR) {
1385 Tcl_AppendResult(bgPtr->interp, "can't read data from ", sinkPtr->name,
1386 ": ", Tcl_PosixError(bgPtr->interp), (char *)NULL);
1387 Tcl_BackgroundError(bgPtr->interp);
1388 return TCL_ERROR;
1389 }
1390 #if WINDEBUG
1391 PurifyPrintf("CollectData %s: done\n", sinkPtr->name);
1392 #endif
1393 return TCL_RETURN;
1394 }
1395
1396 /*
1397 *----------------------------------------------------------------------
1398 *
1399 * CreateSinkHandler --
1400 *
1401 * Creates a file handler for the given sink. The file
1402 * descriptor is also set for non-blocking I/O.
1403 *
1404 * Results:
1405 * None.
1406 *
1407 * Side effects:
1408 * The memory allocated to the BackgroundInfo structure released.
1409 *
1410 *----------------------------------------------------------------------
1411 */
1412 static int
1413 CreateSinkHandler(bgPtr, sinkPtr, proc)
1414 BackgroundInfo *bgPtr;
1415 Sink *sinkPtr;
1416 Tcl_FileProc *proc;
1417 {
1418 #ifndef WIN32
1419 int flags;
1420
1421 flags = fcntl(sinkPtr->fd, F_GETFL);
1422 #ifdef O_NONBLOCK
1423 flags |= O_NONBLOCK;
1424 #else
1425 flags |= O_NDELAY;
1426 #endif
1427 if (fcntl(sinkPtr->fd, F_SETFL, flags) < 0) {
1428 Tcl_AppendResult(bgPtr->interp, "can't set file descriptor ",
1429 Blt_Itoa(sinkPtr->fd), " to non-blocking:",
1430 Tcl_PosixError(bgPtr->interp), (char *)NULL);
1431 return TCL_ERROR;
1432 }
1433 #endif /* WIN32 */
1434 #ifdef FILEHANDLER_USES_TCLFILES
1435 sinkPtr->file = Tcl_GetFile((ClientData)sinkPtr->fd, TCL_UNIX_FD);
1436 Tcl_CreateFileHandler(sinkPtr->file, TCL_READABLE, proc, bgPtr);
1437 #else
1438 Tcl_CreateFileHandler(sinkPtr->fd, TCL_READABLE, proc, bgPtr);
1439 #endif /* FILEHANDLER_USES_TCLFILES */
1440 return TCL_OK;
1441 }
1442
1443 static void
1444 DisableTriggers(bgPtr)
1445 BackgroundInfo *bgPtr; /* Background info record. */
1446 {
1447 int k;
1448
1449 if (bgPtr->traced) {
1450 Tcl_UntraceVar(bgPtr->interp, bgPtr->statVar, TRACE_FLAGS,
1451 VariableProc, bgPtr);
1452 bgPtr->traced = FALSE;
1453 }
1454 if (IsOpenSink(&bgPtr->sink1)) {
1455 CloseSink(bgPtr, bgPtr->interp, &bgPtr->sink1);
1456 }
1457 if (IsOpenSink(&bgPtr->sink2)) {
1458 CloseSink(bgPtr, bgPtr->interp, &bgPtr->sink2);
1459 }
1460 for( k = 0 ; k < bgPtr->nTimers ; k++ ){
1461 Tcl_DeleteTimerHandler(bgPtr->timerTokens[k]);
1462 }
1463 bgPtr->nTimers = 0;
1464 if (bgPtr->donePtr != NULL) {
1465 *bgPtr->donePtr = TRUE;
1466 }
1467 }
1468
1469
1470 /*
1471 *----------------------------------------------------------------------
1472 *
1473 * FreeBackgroundInfo --
1474 *
1475 * Releases the memory allocated for the backgrounded process.
1476 *
1477 *----------------------------------------------------------------------
1478 */
1479 static void
1480 FreeBackgroundInfo(bgPtr)
1481 BackgroundInfo *bgPtr;
1482 {
1483 Blt_FreeSwitches(bgPtr->interp, switchSpecs, (char *)bgPtr, 0);
1484 if (bgPtr->statVar != NULL) {
1485 Blt_Free(bgPtr->statVar);
1486 }
1487 if (bgPtr->procArr != NULL) {
1488 Blt_Free(bgPtr->procArr);
1489 }
1490 if (bgPtr->timerTokens != NULL) {
1491 Blt_Free(bgPtr->timerTokens);
1492 }
1493 Blt_Free(bgPtr);
1494 }
1495
1496 /*
1497 *----------------------------------------------------------------------
1498 *
1499 * DestroyBackgroundInfo --
1500 *
1501 * This procedure is invoked by Tcl_EventuallyFree or Tcl_Release
1502 * to clean up the internal structure (BackgroundInfo) at a safe
1503 * time (when no one is using it anymore).
1504 *
1505 * Results:
1506 * None.b
1507 *
1508 * Side effects:
1509 * The memory allocated to the BackgroundInfo structure released.
1510 *
1511 *----------------------------------------------------------------------
1512 */
1513 /* ARGSUSED */
1514 static void
1515 DestroyBackgroundInfo(bgPtr)
1516 BackgroundInfo *bgPtr; /* Background info record. */
1517 {
1518 Tcl_DontCallWhenDeleted(bgPtr->interp, InterpDeleted, (ClientData)bgPtr);
1519 DisableTriggers(bgPtr);
1520 FreeSinkBuffer(&bgPtr->sink2);
1521 FreeSinkBuffer(&bgPtr->sink1);
1522 if (bgPtr->procArr != NULL) {
1523 register int i;
1524
1525 for (i = 0; i < bgPtr->nProcs; i++) {
1526 if (bgPtr->signalNum > 0) {
1527 kill(bgPtr->procArr[i], bgPtr->signalNum);
1528 }
1529 #ifdef WIN32
1530 Tcl_DetachPids(1, (Tcl_Pid *)&bgPtr->procArr[i].pid);
1531 #else
1532 #if (TCL_MAJOR_VERSION == 7)
1533 Tcl_DetachPids(1, &bgPtr->procArr[i]);
1534 #else
1535 Tcl_DetachPids(1, (Tcl_Pid *)&bgPtr->procArr[i]);
1536 #endif /* TCL_MAJOR_VERSION == 7 */
1537 #endif /* WIN32 */
1538 }
1539 }
1540 FreeBackgroundInfo(bgPtr);
1541 Tcl_ReapDetachedProcs();
1542 }
1543
1544 /*
1545 * ----------------------------------------------------------------------
1546 *
1547 * VariableProc --
1548 *
1549 * Kills all currently running subprocesses (given the specified
1550 * signal). This procedure is called when the user sets the status
1551 * variable associated with this group of child subprocesses.
1552 *
1553 * Results:
1554 * Always returns NULL. Only called from a variable trace.
1555 *
1556 * Side effects:
1557 * The subprocesses are signaled for termination using the
1558 * specified kill signal. Additionally, any resources allocated
1559 * to track the subprocesses is released.
1560 *
1561 * ----------------------------------------------------------------------
1562 */
1563 /* ARGSUSED */
1564 static char *
1565 VariableProc(
1566 ClientData clientData, /* File output information. */
1567 Tcl_Interp *interp,
1568 char *part1,
1569 char *part2, /* Not Used. */
1570 int flags)
1571 {
1572 if (flags & TRACE_FLAGS) {
1573 BackgroundInfo *bgPtr = clientData;
1574
1575 /* Kill all child processes that remain alive. */
1576 if ((bgPtr->procArr != NULL) && (bgPtr->signalNum > 0)) {
1577 register int i;
1578
1579 for (i = 0; i < bgPtr->nProcs; i++) {
1580 kill(bgPtr->procArr[i], bgPtr->signalNum);
1581 }
1582 if (bgPtr->closeKill>0 && bgPtr->nProcs>0) {
1583 bgPtr->cKilled = 1;
1584 AddTimerHandler( bgPtr, bgPtr->closeKill ) ;
1585 }
1586 }
1587 }
1588 return NULL;
1589 }
1590
1591 /*
1592 *----------------------------------------------------------------------
1593 *
1594 * TimerProc --
1595 *
1596 * This is a timer handler procedure which gets called
1597 * periodically to reap any of the sub-processes if they have
1598 * terminated. After the last process has terminated, the
1599 * contents of standard output are stored
1600 * in the output variable, which triggers the cleanup proc (using
1601 * a variable trace). The status the last process to exit is
1602 * written to the status variable.
1603 *
1604 * Results:
1605 * None. Called from the Tcl event loop.
1606 *
1607 * Side effects:
1608 * Many. The contents of procArr is shifted, leaving only those
1609 * sub-processes which have not yet terminated. If there are
1610 * still subprocesses left, this procedure is placed in the timer
1611 * queue again. Otherwise the output and possibly the status
1612 * variables are updated. The former triggers the cleanup
1613 * routine which will destroy the information and resources
1614 * associated with these background processes.
1615 *
1616 *----------------------------------------------------------------------
1617 */
1618 static void
1619 TimerProc(clientData)
1620 ClientData clientData;
1621 {
1622 BackgroundInfo *bgPtr = clientData;
1623 register int i;
1624 unsigned int lastPid;
1625 int pid;
1626 enum PROCESS_STATUS {
1627 PROCESS_EXITED, PROCESS_STOPPED, PROCESS_KILLED, PROCESS_UNKNOWN,
1628 PROCESS_MAX
1629 } pcode;
1630 WAIT_STATUS_TYPE waitStatus, lastStatus;
1631 int nLeft; /* Number of processes still not reaped */
1632 char string[200];
1633 Tcl_DString dString;
1634 int code;
1635 CONST char *result;
1636
1637 lastPid = (unsigned int)-1;
1638 *((int *)&waitStatus) = 0;
1639 *((int *)&lastStatus) = 0;
1640
1641 nLeft = 0;
1642 for (i = 0; i < bgPtr->nProcs; i++) {
1643 #ifdef WIN32
1644 pid = WaitProcess(bgPtr->procArr[i], (int *)&waitStatus, WNOHANG);
1645 #else
1646 pid = waitpid(bgPtr->procArr[i], (int *)&waitStatus, WNOHANG);
1647 #endif
1648 if (pid == 0) { /* Process has not terminated yet */
1649 if (nLeft < i) {
1650 bgPtr->procArr[nLeft] = bgPtr->procArr[i];
1651 }
1652 nLeft++; /* Count the number of processes left */
1653 } else if (pid != -1) {
1654 /*
1655 * Save the status information associated with the subprocess.
1656 * We'll use it only if this is the last subprocess to be reaped.
1657 */
1658 lastStatus = waitStatus;
1659 lastPid = (unsigned int)pid;
1660 }
1661 }
1662 bgPtr->nProcs = nLeft;
1663
1664 if ((nLeft > 0) || (IsOpenSink(&bgPtr->sink1)) ||
1665 (IsOpenSink(&bgPtr->sink2))) {
1666 /* Keep polling for the status of the children that are left */
1667 if (bgPtr->closeKill>0 && bgPtr->cKilled) {
1668 if (IsOpenSink(&bgPtr->sink1)) {
1669 CloseSink(bgPtr, bgPtr->interp, &bgPtr->sink1);
1670 }
1671 if (IsOpenSink(&bgPtr->sink2)) {
1672 CloseSink(bgPtr, bgPtr->interp, &bgPtr->sink2);
1673 }
1674 }
1675 AddTimerHandler( bgPtr, bgPtr->interval ) ;
1676 #if WINDEBUG
1677 PurifyPrintf("schedule TimerProc(nProcs=%d)\n", nLeft);
1678 #endif
1679 return;
1680 }
1681
1682 /*
1683 * All child processes have completed. Set the status variable
1684 * with the status of the last process reaped. The status is a
1685 * list of an error token, the exit status, and a message.
1686 */
1687
1688 code = WEXITSTATUS(lastStatus);
1689 Tcl_DStringInit(&dString);
1690 if (bgPtr->maxExceed) {
1691 Tcl_DStringAppendElement(&dString, "MAXBYTES");
1692 pcode = PROCESS_MAX;
1693 } else if (WIFEXITED(lastStatus)) {
1694 Tcl_DStringAppendElement(&dString, "EXITED");
1695 pcode = PROCESS_EXITED;
1696 } else if (WIFSIGNALED(lastStatus)) {
1697 Tcl_DStringAppendElement(&dString, "KILLED");
1698 pcode = PROCESS_KILLED;
1699 code = -1;
1700 } else if (WIFSTOPPED(lastStatus)) {
1701 Tcl_DStringAppendElement(&dString, "STOPPED");
1702 pcode = PROCESS_STOPPED;
1703 code = -1;
1704 } else {
1705 Tcl_DStringAppendElement(&dString, "UNKNOWN");
1706 pcode = PROCESS_UNKNOWN;
1707 }
1708 #ifdef WIN32
1709 sprintf(string, "%u", lastPid);
1710 Tcl_DStringAppendElement(&dString, string);
1711 #else
1712 Tcl_DStringAppendElement(&dString, Blt_Itoa(lastPid));
1713 #endif
1714 Tcl_DStringAppendElement(&dString, Blt_Itoa(code));
1715 switch(pcode) {
1716 case PROCESS_MAX:
1717 Tcl_DStringAppendElement(&dString, "max bytes exceeded");
1718 break;
1719 case PROCESS_EXITED:
1720 if (bgPtr->cKilled) {
1721 Tcl_DStringAppendElement(&dString, "kill signal");
1722 } else {
1723 Tcl_DStringAppendElement(&dString, "child completed normally");
1724 }
1725 break;
1726 case PROCESS_KILLED:
1727 Tcl_DStringAppendElement(&dString,
1728 Tcl_SignalMsg((int)(WTERMSIG(lastStatus))));
1729 break;
1730 case PROCESS_STOPPED:
1731 Tcl_DStringAppendElement(&dString,
1732 Tcl_SignalMsg((int)(WSTOPSIG(lastStatus))));
1733 break;
1734 case PROCESS_UNKNOWN:
1735 sprintf(string, "child completed with unknown status 0x%x",
1736 *((int *)&lastStatus));
1737 Tcl_DStringAppendElement(&dString, string);
1738 break;
1739 }
1740 if (bgPtr->exitCodePtr != NULL) {
1741 *bgPtr->exitCodePtr = code;
1742 }
1743 DisableTriggers(bgPtr);
1744 result = Tcl_SetVar(bgPtr->interp, bgPtr->statVar,
1745 Tcl_DStringValue(&dString), bgPtr->varFlags | TCL_LEAVE_ERR_MSG);
1746 SinkCallback(bgPtr->interp, &bgPtr->sink1, Tcl_DStringValue(&dString));
1747 Tcl_DStringFree(&dString);
1748 if (result == NULL) {
1749 Tcl_BackgroundError(bgPtr->interp);
1750 }
1751 if (bgPtr->detached) {
1752 DestroyBackgroundInfo(bgPtr);
1753 }
1754 }
1755
1756 /*
1757 *----------------------------------------------------------------------
1758 *
1759 * Stdoutproc --
1760 *
1761 * This procedure is called when output from the detached pipeline
1762 * is available. The output is read and saved in a buffer in the
1763 * BackgroundInfo structure.
1764 *
1765 * Results:
1766 * None.
1767 *
1768 * Side effects:
1769 * Data is stored in the buffer. This character array may
1770 * be increased as more space is required to contain the output
1771 * of the pipeline.
1772 *
1773 *----------------------------------------------------------------------
1774 */
1775 /* ARGSUSED */
1776 static void
1777 StdoutProc(clientData, mask)
1778 ClientData clientData; /* File output information. */
1779 int mask; /* Not used. */
1780 {
1781 BackgroundInfo *bgPtr = clientData;
1782
1783 if (CollectData(bgPtr, &bgPtr->sink1) == TCL_OK) {
1784 return;
1785 }
1786 /*
1787 * Either EOF or an error has occurred. In either case, close the
1788 * sink. Note that closing the sink will also remove the file
1789 * handler, so this routine will not be called again.
1790 */
1791 CloseSink(bgPtr, bgPtr->interp, &bgPtr->sink1);
1792
1793 /*
1794 * If both sinks (stdout and stderr) are closed, this doesn't
1795 * necessarily mean that the process has terminated. Set up a
1796 * timer handler to periodically poll for the exit status of each
1797 * process. Initially check at the next idle interval.
1798 */
1799 if (!IsOpenSink(&bgPtr->sink2)) {
1800 AddTimerHandler( bgPtr, 0 ) ;
1801 }
1802 }
1803
1804 /*
1805 *----------------------------------------------------------------------
1806 *
1807 * StderrProc --
1808 *
1809 * This procedure is called when error from the detached pipeline
1810 * is available. The error is read and saved in a buffer in the
1811 * BackgroundInfo structure.
1812 *
1813 * Results:
1814 * None.
1815 *
1816 * Side effects:
1817 * Data is stored in the buffer. This character array may
1818 * be increased as more space is required to contain the stderr
1819 * of the pipeline.
1820 *
1821 *----------------------------------------------------------------------
1822 */
1823 /* ARGSUSED */
1824 static void
1825 StderrProc(clientData, mask)
1826 ClientData clientData; /* File output information. */
1827 int mask; /* Not used. */
1828 {
1829 BackgroundInfo *bgPtr = clientData;
1830
1831 if (CollectData(bgPtr, &bgPtr->sink2) == TCL_OK) {
1832 return;
1833 }
1834 /*
1835 * Either EOF or an error has occurred. In either case, close the
1836 * sink. Note that closing the sink will also remove the file
1837 * handler, so this routine will not be called again.
1838 */
1839 CloseSink(bgPtr, bgPtr->interp, &bgPtr->sink2);
1840
1841 /*
1842 * If both sinks (stdout and stderr) are closed, this doesn't
1843 * necessarily mean that the process has terminated. Set up a
1844 * timer handler to periodically poll for the exit status of each
1845 * process. Initially check at the next idle interval.
1846 */
1847 if (!IsOpenSink(&bgPtr->sink1)) {
1848 AddTimerHandler( bgPtr, 0 ) ;
1849 }
1850 }
1851
1852 static void
1853 AddTimerHandler( bgPtr, interval )
1854 BackgroundInfo *bgPtr;
1855 int interval;
1856 {
1857 if(!(bgPtr->timerTokens)){
1858 bgPtr->timerTokens = Blt_Calloc(EXPECTED_NUM_TIMERS, sizeof(Tcl_TimerToken *));
1859 }
1860 if( ++bgPtr->nTimers >= EXPECTED_NUM_TIMERS ){
1861 bgPtr->timerTokens = Blt_Realloc( bgPtr->timerTokens,
1862 bgPtr->nTimers * sizeof(Tcl_TimerToken *) ) ;
1863 }
1864 bgPtr->timerTokens[bgPtr->nTimers-1] = Tcl_CreateTimerHandler(interval,
1865 TimerProc,
1866 bgPtr);
1867 }
1868
1869 static void
1870 InterpDeleted(clientData, interp)
1871 ClientData clientData; /* Thread-specific data. */
1872 Tcl_Interp *interp; /* Current interpreter. */
1873 {
1874 BackgroundInfo *bgPtr = (BackgroundInfo *)clientData;
1875 DestroyBackgroundInfo(bgPtr);
1876 }
1877
1878 void
1879 MakeLocal( char *ns, char **str) {
1880 Tcl_DString dStr;
1881 if (ns == NULL) return;
1882 if (!strcmp(ns,"::")) return;
1883 if (!strncmp(*str,"::",2)) return;
1884 Tcl_DStringInit(&dStr);
1885 Tcl_DStringAppend(&dStr, ns, -1);
1886 Tcl_DStringAppend(&dStr, "::", -1);
1887 Tcl_DStringAppend(&dStr, *str, -1);
1888 Blt_Free(*str);
1889 *str = Blt_Strdup( Tcl_DStringValue(&dStr) );
1890 Tcl_DStringFree(&dStr);
1891 }
1892 /*
1893 *----------------------------------------------------------------------
1894 *
1895 * BgexecCmd --
1896 *
1897 * This procedure is invoked to process the "bgexec" Tcl command.
1898 * See the user documentation for details on what it does.
1899 *
1900 * Results:
1901 * A standard Tcl result.
1902 *
1903 * Side effects:
1904 * See the user documentation.
1905 *
1906 *----------------------------------------------------------------------
1907 */
1908 /* ARGSUSED */
1909 static int
1910 BgexecCmd(clientData, interp, argc, argv)
1911 ClientData clientData; /* Thread-specific data. */
1912 Tcl_Interp *interp; /* Current interpreter. */
1913 int argc; /* Number of arguments. */
1914 char **argv; /* Argument strings. */
1915 {
1916 int *outFdPtr, *errFdPtr;
1917 int nProcs;
1918 Process *pidPtr;
1919 char *lastArg;
1920 BackgroundInfo *bgPtr;
1921 int i, term = 0, tail = 0;
1922 int detached;
1923 Tcl_Encoding encoding;
1924
1925 if (argc < 3) {
1926 Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
1927 " varName ?options? command ?arg...?\"", (char *)NULL);
1928 return TCL_ERROR;
1929 }
1930
1931 /* Check if the command line is to be run detached (the last
1932 * argument is "&") */
1933 lastArg = argv[argc - 1];
1934 detached = ((lastArg[0] == '&') && (lastArg[1] == '\0'));
1935 if (detached) {
1936 argc--;
1937 argv[argc] = NULL; /* Remove the '&' argument */
1938 }
1939 bgPtr = Blt_Calloc(1, sizeof(BackgroundInfo));
1940 assert(bgPtr);
1941
1942 /* Initialize the background information record */
1943 bgPtr->interp = interp;
1944 bgPtr->signalNum = SIGKILL;
1945 bgPtr->nProcs = -1;
1946 bgPtr->interval = 1000;
1947 bgPtr->detached = detached;
1948 bgPtr->keepNewline = TRUE;
1949 bgPtr->statVar = Blt_Strdup(argv[1]);
1950 bgPtr->timerTokens = NULL;
1951 bgPtr->nTimers = 0;
1952 bgPtr->closeKill = 0;
1953
1954 /* Try to clean up any detached processes */
1955 Tcl_ReapDetachedProcs();
1956
1957 for (i=2; i<argc; i += 2) {
1958 if (!strcmp(argv[i],"--")) {
1959 term = i+1;
1960 tail = (argc-i);
1961 break;
1962 }
1963 }
1964 i = Blt_ProcessSwitches(interp, switchSpecs, argc - 2 - tail, argv + 2,
1965 (char *)bgPtr, BLT_SWITCH_ARGV_PARTIAL);
1966 if (i < 0) {
1967 FreeBackgroundInfo(bgPtr);
1968 return TCL_ERROR;
1969 }
1970 bgPtr->varFlags = TCL_GLOBAL_ONLY;
1971 if (bgPtr->localVars) {
1972 if (detached) {
1973 bgPtr->varFlags = TCL_NAMESPACE_ONLY;
1974 } else {
1975 bgPtr->varFlags = 0;
1976 }
1977 }
1978 if (term) {
1979 i = term;
1980 } else {
1981 i += 2;
1982 }
1983 /* Must be at least one argument left as the command to execute. */
1984 if (argc <= i) {
1985 Tcl_AppendResult(interp, "missing command to execute: should be \"",
1986 argv[0], " varName ?options? command ?arg...?\"", (char *)NULL);
1987 FreeBackgroundInfo(bgPtr);
1988 return TCL_ERROR;
1989 }
1990
1991 if (bgPtr->localVars && (detached)) {
1992 char *ns = NULL;
1993 Tcl_Namespace *nsPtr;
1994 nsPtr = Tcl_GetCurrentNamespace(interp);
1995
1996 if (nsPtr != NULL) {
1997 ns = nsPtr->fullName;
1998 }
1999 if (bgPtr->statVar) MakeLocal(ns, &bgPtr->statVar);
2000 if (bgPtr->sink1.doneVar) MakeLocal(ns, &bgPtr->sink1.doneVar);
2001 if (bgPtr->sink1.command) MakeLocal(ns, &bgPtr->sink1.command);
2002 if (bgPtr->sink1.updateVar) MakeLocal(ns, &bgPtr->sink1.updateVar);
2003 if (bgPtr->sink2.doneVar) MakeLocal(ns, &bgPtr->sink2.doneVar);
2004 if (bgPtr->sink2.command) MakeLocal(ns, &bgPtr->sink2.command);
2005 if (bgPtr->sink2.updateVar) MakeLocal(ns, &bgPtr->sink2.updateVar);
2006 }
2007
2008 /* Put a trace on the exit status variable. The will also allow
2009 * the user to prematurely terminate the pipeline by simply
2010 * setting it. */
2011 if (Tcl_TraceVar(interp, bgPtr->statVar, TRACE_FLAGS, VariableProc, bgPtr) != TCL_OK) {
2012 FreeBackgroundInfo(bgPtr);
2013 return TCL_ERROR;
2014 }
2015 bgPtr->traced = TRUE;
2016
2017 encoding = ENCODING_ASCII;
2018 if (bgPtr->outputEncodingName != NULL) {
2019 if (strcmp(bgPtr->outputEncodingName, "binary") == 0) {
2020 encoding = ENCODING_BINARY;
2021 } else {
2022 #if (TCL_VERSION_NUMBER >= _VERSION(8,1,0))
2023 encoding = Tcl_GetEncoding(interp, bgPtr->outputEncodingName);
2024 if (encoding == NULL) {
2025 goto error;
2026 }
2027 #endif
2028 }
2029 }
2030 InitSink(bgPtr, &bgPtr->sink1, "stdout", encoding);
2031 if (bgPtr->errorEncodingName != NULL) {
2032 if (strcmp(bgPtr->errorEncodingName, "binary") == 0) {
2033 encoding = ENCODING_BINARY;
2034 } else {
2035 #if (TCL_VERSION_NUMBER >= _VERSION(8,1,0))
2036 encoding = Tcl_GetEncoding(interp, bgPtr->errorEncodingName);
2037 if (encoding == NULL) {
2038 goto error;
2039 }
2040 #endif
2041 }
2042 }
2043 InitSink(bgPtr, &bgPtr->sink2, "stderr", encoding);
2044
2045 outFdPtr = errFdPtr = (int *)NULL;
2046 #ifdef WIN32
2047 if ((!bgPtr->detached) ||
2048 (bgPtr->sink1.doneVar != NULL) ||
2049 (bgPtr->sink1.command != NULL) ||
2050 (bgPtr->sink1.updateVar != NULL) ||
2051 (bgPtr->sink1.updateCmd != NULL)) {
2052 outFdPtr = &bgPtr->sink1.fd;
2053 }
2054 #else
2055 outFdPtr = &bgPtr->sink1.fd;
2056 #endif
2057 if ((bgPtr->sink2.doneVar != NULL) ||
2058 (bgPtr->sink2.updateVar != NULL) ||
2059 (bgPtr->sink2.updateCmd != NULL) ||
2060 (bgPtr->sink2.echo)) {
2061 errFdPtr = &bgPtr->sink2.fd;
2062 }
2063 nProcs = Blt_CreatePipeline(interp, argc - i, argv + i, &pidPtr,
2064 (int *)NULL, outFdPtr, errFdPtr);
2065 if (nProcs < 0) {
2066 goto error;
2067 }
2068 bgPtr->procArr = pidPtr;
2069 bgPtr->nProcs = nProcs;
2070
2071 if (bgPtr->sink1.fd == -1) {
2072
2073 /* If output has been redirected, start polling immediately
2074 * for the exit status of each process. Normally, this is
2075 * done only after stdout has been closed by the last process,
2076 * but here stdout has been redirected. The default polling
2077 * interval is every 1 second. */
2078
2079 AddTimerHandler( bgPtr, bgPtr->interval ) ;
2080
2081 } else if (CreateSinkHandler(bgPtr, &bgPtr->sink1, StdoutProc) != TCL_OK) {
2082 goto error;
2083 }
2084 if ((bgPtr->sink2.fd != -1) &&
2085 (CreateSinkHandler(bgPtr, &bgPtr->sink2, StderrProc) != TCL_OK)) {
2086 goto error;
2087 }
2088 Tcl_CallWhenDeleted(interp, InterpDeleted, (ClientData)bgPtr);
2089 if (bgPtr->detached) {
2090 char string[200];
2091
2092 /* If detached, return a list of the child process ids instead
2093 * of the output of the pipeline. */
2094 for (i = 0; i < nProcs; i++) {
2095 #ifdef WIN32
2096 sprintf(string, "%u", (unsigned int)bgPtr->procArr[i].pid);
2097 #else
2098 sprintf(string, "%d", bgPtr->procArr[i]);
2099 #endif
2100 Tcl_AppendElement(interp, string);
2101 }
2102 } else {
2103 int exitCode;
2104 int done, doRaise;
2105
2106 bgPtr->exitCodePtr = &exitCode;
2107 bgPtr->donePtr = &done;
2108
2109 exitCode = done = 0;
2110 while (!done) {
2111 Tcl_DoOneEvent(0);
2112 }
2113 DisableTriggers(bgPtr);
2114 if ((exitCode == 0 || bgPtr->doRaise==0) && (bgPtr->sink1.doneVar == NULL) && (bgPtr->sink1.command == NULL)) {
2115 unsigned char *data;
2116 size_t length;
2117
2118 /* Return the output of the pipeline. */
2119 GetSinkData(&bgPtr->sink1, &data, &length);
2120 #if (TCL_VERSION_NUMBER < _VERSION(8,1,0))
2121 data[length] = '\0';
2122 Tcl_SetResult(interp, data, TCL_VOLATILE);
2123 #else
2124 Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(data, length));
2125 #endif
2126 }
2127 /* Clean up resources used. */
2128 doRaise = bgPtr->doRaise;
2129 DestroyBackgroundInfo(bgPtr);
2130 if ((doRaise) && exitCode != 0) {
2131 Tcl_AppendResult(interp, "child process exited abnormally",
2132 (char *)NULL);
2133 return TCL_ERROR;
2134 }
2135 }
2136 return TCL_OK;
2137 error:
2138 DisableTriggers(bgPtr);
2139 DestroyBackgroundInfo(bgPtr);
2140 return TCL_ERROR;
2141 }
2142
2143
2144 static int
2145 KillCmd(clientData, interp, argc, argv)
2146 ClientData clientData; /* Thread-specific data. */
2147 Tcl_Interp *interp; /* Current interpreter. */
2148 int argc; /* Number of arguments. */
2149 char **argv; /* Argument strings. */
2150 {
2151 char *string;
2152 int signalNum = SIGKILL;
2153 int pid;
2154 #ifdef WIN32
2155 HANDLE h;
2156 #endif
2157
2158 if (argc>3) {
2159 Tcl_AppendResult(interp, "too many args", 0);
2160 return TCL_ERROR;
2161 }
2162 if (argc<2) {
2163 Tcl_AppendResult(interp, "pid required", 0);
2164 return TCL_ERROR;
2165 }
2166 if (Tcl_GetInt(interp, argv[1], &pid) != TCL_OK) {
2167 return TCL_ERROR;
2168 }
2169
2170 #ifdef WIN32
2171 if (argc!=2) {
2172 Tcl_AppendResult(interp, "windows does not support signo", 0);
2173 return TCL_ERROR;
2174 }
2175 if (!(h = OpenProcess (PROCESS_TERMINATE, 0, pid))) {
2176 Tcl_AppendResult (interp, "invalid pid or access", NULL);
2177 return TCL_ERROR;
2178 }
2179
2180 if (TerminateProcess (h, 1) == 0) {
2181 Tcl_AppendResult (interp, "TerminateProcess failure", NULL);
2182 return TCL_ERROR;
2183 }
2184
2185 CloseHandle (h);
2186 #else
2187 if (argc==3) {
2188 string = argv[2];
2189 if (isdigit(UCHAR(string[0]))) {
2190 if (Tcl_GetInt(interp, string, &signalNum) != TCL_OK) {
2191 return TCL_ERROR;
2192 }
2193 } else {
2194 char *name;
2195 register SignalId *sigPtr;
2196
2197 name = string;
2198
2199 /* Clip off any "SIG" prefix from the signal name */
2200 if ((name[0] == 'S') && (name[1] == 'I') && (name[2] == 'G')) {
2201 name += 3;
2202 }
2203 signalNum = -1;
2204 for (sigPtr = signalIds; sigPtr->number > 0; sigPtr++) {
2205 if (strcmp(sigPtr->name + 3, name) == 0) {
2206 signalNum = sigPtr->number;
2207 break;
2208 }
2209 }
2210 if (signalNum < 0) {
2211 Tcl_AppendResult(interp, "unknown signal \"", string, "\"",
2212 (char *)NULL);
2213 return TCL_ERROR;
2214 }
2215 }
2216 if ((signalNum < 0) || (signalNum > NSIG)) {
2217 /* Outside range of signals */
2218 Tcl_AppendResult(interp, "signal number \"", string,
2219 "\" is out of range", (char *)NULL);
2220 return TCL_ERROR;
2221 }
2222 }
2223 kill(pid, signalNum);
2224 #endif
2225 return TCL_OK;
2226 }
2227
2228 /*
2229 *----------------------------------------------------------------------
2230 *
2231 * Blt_BgexecInit --
2232 *
2233 * This procedure is invoked to initialize the "bgexec" Tcl
2234 * command. See the user documentation for details on what it
2235 * does.
2236 *
2237 * Results:
2238 * None.
2239 *
2240 * Side effects:
2241 * See the user documentation.
2242 *
2243 *----------------------------------------------------------------------
2244 */
2245 int
2246 Blt_BgexecInit(interp)
2247 Tcl_Interp *interp;
2248 {
2249 static Blt_CmdSpec cmdSpec = {"bgexec", BgexecCmd, };
2250 static Blt_CmdSpec cmdSpec2 = {"kill", KillCmd, };
2251
2252 if (Blt_InitCmd(interp, "blt", &cmdSpec) == NULL) {
2253 return TCL_ERROR;
2254 }
2255 if (Blt_InitCmd(interp, "blt", &cmdSpec2) == NULL) {
2256 return TCL_ERROR;
2257 }
2258 return TCL_OK;
2259 }
2260 #endif /* NO_BGEXEC */