Debian Codegraph @

generic/bltBgexec.c

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 3 — not the installed (fully patched) source.
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 return NULL;
563 }
564
565 /*
566 *----------------------------------------------------------------------
567 *
568 * NextLine --
569 *
570 * Returns the next line of data.
571 *
572 *----------------------------------------------------------------------
573 */
574 static unsigned char *
575 NextLine(sinkPtr, lengthPtr)
576 Sink *sinkPtr;
577 int *lengthPtr;
578 {
579 if (sinkPtr->mark > sinkPtr->lastMark) {
580 unsigned char *string;
581 int newBytes;
582 register int i;
583
584 string = sinkPtr->byteArr + sinkPtr->lastMark;
585 newBytes = sinkPtr->mark - sinkPtr->lastMark;
586 for (i = 0; i < newBytes; i++) {
587 if (string[i] == '\n') {
588 int length;
589
590 length = i + 1;
591 sinkPtr->lastMark += length;
592 if (!(sinkPtr->flags & SINK_KEEP_NL)) {
593 length--; /* Backup over the newline. */
594 }
595 *lengthPtr = length;
596 return string;
597 }
598 }
599 /* Newline not found. On errors or EOF, also return a partial line. */
600 if (sinkPtr->status < 0) {
601 *lengthPtr = newBytes;
602 sinkPtr->lastMark = sinkPtr->mark;
603 return string;
604 }
605 }
606 return NULL;
607 }
608 /*
609 *----------------------------------------------------------------------
610 *
611 * ResetSink --
612 *
613 * Removes the bytes already processed from the buffer, possibly
614 * resetting it to empty. This used when we don't care about
615 * keeping all the data collected from the channel (no -output
616 * flag and the process is detached).
617 *
618 *----------------------------------------------------------------------
619 */
620 static void
621 ResetSink(sinkPtr)
622 Sink *sinkPtr;
623 {
624 if ((sinkPtr->flags & SINK_BUFFERED) &&
625 (sinkPtr->fill > sinkPtr->lastMark)) {
626 register size_t i, j;
627
628 /* There may be bytes remaining in the buffer, awaiting
629 * another read before we see the next newline. So move the
630 * bytes to the front of the array. */
631
632 for (i = 0, j = sinkPtr->lastMark; j < sinkPtr->fill; i++, j++) {
633 sinkPtr->byteArr[i] = sinkPtr->byteArr[j];
634 }
635 /* Move back the fill point and processed point. */
636 sinkPtr->fill -= sinkPtr->lastMark;
637 sinkPtr->mark -= sinkPtr->lastMark;
638 } else {
639 sinkPtr->mark = sinkPtr->fill = 0;
640 }
641 sinkPtr->lastMark = 0;
642 }
643
644 /*
645 *----------------------------------------------------------------------
646 *
647 * InitSink --
648 *
649 * Initializes the buffer's storage.
650 *
651 * Results:
652 * None.
653 *
654 * Side effects:
655 * Storage is cleared.
656 *
657 *----------------------------------------------------------------------
658 */
659 static void
660 InitSink(bgPtr, sinkPtr, name, encoding)
661 BackgroundInfo *bgPtr;
662 Sink *sinkPtr;
663 char *name;
664 Tcl_Encoding encoding;
665 {
666 sinkPtr->name = name;
667 sinkPtr->echo = FALSE;
668 sinkPtr->fd = -1;
669 sinkPtr->file = (Tcl_File)NULL;
670 sinkPtr->byteArr = sinkPtr->staticSpace;
671 sinkPtr->size = DEF_BUFFER_SIZE;
672 sinkPtr->encoding = encoding;
673 if (bgPtr->keepNewline) {
674 sinkPtr->flags |= SINK_KEEP_NL;
675 }
676 if (bgPtr->lineBuffered) {
677 sinkPtr->flags |= SINK_BUFFERED;
678 }
679 if ((sinkPtr->updateCmd != NULL) ||
680 (sinkPtr->updateVar != NULL) ||
681 (sinkPtr->echo)) {
682 sinkPtr->flags |= SINK_NOTIFY;
683 }
684 #if (TCL_MAJOR_VERSION >= 8)
685 if (sinkPtr->updateCmd != NULL) {
686 Tcl_Obj **objArr;
687 char **p;
688 int count;
689 register int i;
690
691 count = 0;
692 for (p = sinkPtr->updateCmd; *p != NULL; p++) {
693 count++;
694 }
695 objArr = Blt_Malloc((count + 1) * sizeof(Tcl_Obj *));
696 for (i = 0; i < count; i++) {
697 objArr[i] = Tcl_NewStringObj(sinkPtr->updateCmd[i], -1);
698 Tcl_IncrRefCount(objArr[i]);
699 }
700 sinkPtr->objv = objArr;
701 sinkPtr->objc = count + 1;
702 }
703 #endif
704 ResetSink(sinkPtr);
705 }
706
707 /*
708 *----------------------------------------------------------------------
709 *
710 * FreeSinkBuffer --
711 *
712 * Frees the buffer's storage, freeing any malloc'ed space.
713 *
714 * Results:
715 * None.
716 *
717 *----------------------------------------------------------------------
718 */
719 static void
720 FreeSinkBuffer(sinkPtr)
721 Sink *sinkPtr;
722 {
723 if (sinkPtr->byteArr != sinkPtr->staticSpace) {
724 Blt_Free(sinkPtr->byteArr);
725 }
726 sinkPtr->fd = -1;
727 sinkPtr->file = (Tcl_File)NULL;
728 #if (TCL_MAJOR_VERSION >= 8)
729 if (sinkPtr->objv != NULL) {
730 register int i;
731
732 for (i = 0; i < sinkPtr->objc - 1; i++) {
733 Tcl_DecrRefCount(sinkPtr->objv[i]);
734 }
735 Blt_Free(sinkPtr->objv);
736 }
737 #endif
738 }
739
740
741 /*
742 *----------------------------------------------------------------------
743 *
744 * ExtendSinkBuffer --
745 *
746 * Doubles the size of the current buffer.
747 *
748 * Results:
749 * None.
750 *
751 *----------------------------------------------------------------------
752 */
753 static int
754 ExtendSinkBuffer(sinkPtr)
755 Sink *sinkPtr;
756 {
757 unsigned char *arrayPtr;
758 register unsigned char *srcPtr, *destPtr, *endPtr;
759 /*
760 * Allocate a new array, double the old size
761 */
762 sinkPtr->size += sinkPtr->size;
763 arrayPtr = Blt_Malloc(sizeof(unsigned char) * sinkPtr->size);
764 if (arrayPtr == NULL) {
765 return -1;
766 }
767 srcPtr = sinkPtr->byteArr;
768 endPtr = sinkPtr->byteArr + sinkPtr->fill;
769 destPtr = arrayPtr;
770 while (srcPtr < endPtr) {
771 *destPtr++ = *srcPtr++;
772 }
773 if (sinkPtr->byteArr != sinkPtr->staticSpace) {
774 Blt_Free(sinkPtr->byteArr);
775 }
776 sinkPtr->byteArr = arrayPtr;
777
778 return (sinkPtr->size - sinkPtr->fill); /* Return bytes left. */
779 }
780
781 /*
782 *----------------------------------------------------------------------
783 *
784 * ReadBytes --
785 *
786 * Reads and appends any available data from a given file descriptor
787 * to the buffer.
788 *
789 * Results:
790 * Returns TCL_OK when EOF is found, TCL_RETURN if reading
791 * data would block, and TCL_ERROR if an error occurred.
792 *
793 *----------------------------------------------------------------------
794 */
795 static void
796 ReadBytes(bgPtr, sinkPtr)
797 BackgroundInfo *bgPtr;
798 Sink *sinkPtr;
799 {
800 int nBytes, bytesLeft;
801 register int i;
802 unsigned char *array;
803
804 /*
805 * ------------------------------------------------------------------
806 *
807 * Worry about indefinite postponement.
808 *
809 * Typically we want to stay in the read loop as long as it takes
810 * to collect all the data that's currently available. But if
811 * it's coming in at a constant high rate, we need to arbitrarily
812 * break out at some point. This allows for both setting the
813 * update variable and the Tk program to handle idle events.
814 *
815 * ------------------------------------------------------------------
816 */
817
818 for (i = 0; i < MAX_READS; i++) {
819
820 /* Allocate a larger buffer when the number of remaining bytes
821 * is below the threshold BLOCK_SIZE. */
822
823 bytesLeft = sinkPtr->size - sinkPtr->fill;
824
825 if (bytesLeft < BLOCK_SIZE) {
826 bytesLeft = ExtendSinkBuffer(sinkPtr);
827 if (bytesLeft < 0) {
828 sinkPtr->status = READ_ERROR;
829 return;
830 }
831 }
832 array = sinkPtr->byteArr + sinkPtr->fill;
833
834 /*
835 * Read into a buffer but make sure we leave room for a
836 * trailing NUL byte.
837 */
838 nBytes = read(sinkPtr->fd, array, bytesLeft - 1);
839 if (nBytes == 0) { /* EOF: break out of loop. */
840 sinkPtr->status = READ_EOF;
841 return;
842 }
843 if (nBytes < 0) {
844 #ifdef O_NONBLOCK
845 #define BLOCKED EAGAIN
846 #else
847 #define BLOCKED EWOULDBLOCK
848 #endif /*O_NONBLOCK*/
849 /* Either an error has occurred or no more data is
850 * currently available to read. */
851 if (errno == BLOCKED) {
852 sinkPtr->status = READ_AGAIN;
853 return;
854 }
855 sinkPtr->byteArr[0] = '\0';
856 sinkPtr->status = READ_ERROR;
857 return;
858 }
859 sinkPtr->fill += nBytes;
860 sinkPtr->byteArr[sinkPtr->fill] = '\0';
861 }
862 sinkPtr->status = nBytes;
863 }
864
865 #define IsOpenSink(sinkPtr) ((sinkPtr)->fd != -1)
866
867 static void
868 CloseSink(bgPtr, interp, sinkPtr)
869 BackgroundInfo *bgPtr;
870 Tcl_Interp *interp;
871 Sink *sinkPtr;
872 {
873 unsigned char *data = NULL;
874 size_t length;
875
876 if (IsOpenSink(sinkPtr)) {
877 close(sinkPtr->fd);
878 #ifdef FILEHANDLER_USES_TCLFILES
879 Tcl_DeleteFileHandler(sinkPtr->file);
880 Tcl_FreeFile(sinkPtr->file);
881 #else
882 Tcl_DeleteFileHandler(sinkPtr->fd);
883 #endif
884 sinkPtr->file = (Tcl_File)NULL;
885 sinkPtr->fd = -1;
886
887 #if WINDEBUG
888 PurifyPrintf("CloseSink: set done var %s\n", sinkPtr->name);
889 #endif
890 if (sinkPtr->doneVar != NULL && !Tcl_InterpDeleted(interp)) {
891 /*
892 * If data is to be collected, set the "done" variable
893 * with the contents of the buffer.
894 */
895 GetSinkData(sinkPtr, &data, &length);
896 #if (TCL_VERSION_NUMBER < _VERSION(8,1,0))
897 data[length] = '\0';
898 if (Tcl_SetVar(interp, sinkPtr->doneVar, data,
899 bgPtr->varFlags) == NULL) {
900 Tcl_BackgroundError(interp);
901 }
902 #else
903 if (Tcl_SetVar2Ex(interp, sinkPtr->doneVar, NULL,
904 Tcl_NewByteArrayObj(data, length),
905 (bgPtr->varFlags | TCL_LEAVE_ERR_MSG)) == NULL) {
906 Tcl_BackgroundError(interp);
907 }
908 #endif
909 }
910 #if WINDEBUG
911 PurifyPrintf("CloseSink %s: done\n", sinkPtr->name);
912 #endif
913 }
914 }
915
916 static void
917 SinkCallback(interp, sinkPtr, status)
918 Tcl_Interp *interp;
919 Sink *sinkPtr;
920 char *status;
921 {
922 unsigned char *data = NULL;
923 size_t length;
924 if (sinkPtr->command != NULL && !Tcl_InterpDeleted(interp)) {
925 Tcl_DString dStr;
926 Tcl_DStringInit(&dStr);
927 GetSinkData(sinkPtr, &data, &length);
928 Tcl_DStringAppend(&dStr, sinkPtr->command, -1);
929 Tcl_DStringAppendElement(&dStr, data);
930 Tcl_DStringAppendElement(&dStr, status);
931 if (Tcl_GlobalEval(interp, Tcl_DStringValue(&dStr)) != TCL_OK) {
932 Tcl_BackgroundError(interp);
933 }
934 Tcl_DStringFree(&dStr);
935 }
936 }
937 /*
938 *----------------------------------------------------------------------
939 *
940 * CookSink --
941 *
942 * For Windows, translate CR/NL combinations to NL alone.
943 *
944 * Results:
945 * None.
946 *
947 * Side Effects:
948 * The size of the byte array may shrink and array contents
949 * shifted as carriage returns are found and removed.
950 *
951 *----------------------------------------------------------------------
952 */
953 static void
954 CookSink(interp, sinkPtr)
955 Tcl_Interp *interp;
956 Sink *sinkPtr;
957 {
958 unsigned char *srcPtr, *endPtr;
959 #ifdef WIN32
960 size_t oldMark;
961
962 oldMark = sinkPtr->mark;
963 #endif
964 if (sinkPtr->encoding == ENCODING_BINARY) { /* binary */
965 /* No translation needed. */
966 sinkPtr->mark = sinkPtr->fill;
967 } else if (sinkPtr->encoding == ENCODING_ASCII) { /* ascii */
968 #if (TCL_VERSION_NUMBER < _VERSION(8,1,0))
969 /* Convert NUL bytes to question marks. */
970 srcPtr = sinkPtr->byteArr + sinkPtr->mark;
971 endPtr = sinkPtr->byteArr + sinkPtr->fill;
972 while (srcPtr < endPtr) {
973 if (*srcPtr == '\0') {
974 *srcPtr = '?';
975 }
976 srcPtr++;
977 }
978 #endif /* < 8.1.0 */
979 /* One-to-one translation. mark == fill. */
980 sinkPtr->mark = sinkPtr->fill;
981 #if (TCL_VERSION_NUMBER >= _VERSION(8,1,0))
982 } else { /* unicode. */
983 int nSrcCooked, nCooked;
984 int result;
985 size_t cookedSize, spaceLeft, needed;
986 size_t nRaw, nLeftOver;
987 unsigned char *destPtr;
988 unsigned char *raw, *cooked;
989 unsigned char leftover[100];
990
991 raw = sinkPtr->byteArr + sinkPtr->mark;
992 nRaw = sinkPtr->fill - sinkPtr->mark;
993 /* Ideally, the cooked buffer size should be smaller */
994 cookedSize = nRaw * TCL_UTF_MAX + 1;
995 cooked = Blt_Malloc(cookedSize);
996 result = Tcl_ExternalToUtf(interp, sinkPtr->encoding,
997 (char *)raw, nRaw, 0, NULL, (char *)cooked,
998 cookedSize, &nSrcCooked, &nCooked, NULL);
999 nLeftOver = 0;
1000 if (result == TCL_CONVERT_MULTIBYTE) {
1001 /*
1002 * Last multibyte sequence wasn't completed. Save the
1003 * extra characters in a temporary buffer.
1004 */
1005 nLeftOver = (nRaw - nSrcCooked);
1006 srcPtr = sinkPtr->byteArr + (sinkPtr->mark + nSrcCooked);
1007 endPtr = srcPtr + nLeftOver;
1008 destPtr = leftover;
1009 while (srcPtr < endPtr) {
1010 *destPtr++ = *srcPtr++;
1011 }
1012 }
1013 /*
1014 * Create a bigger
1015 */
1016
1017 needed = nLeftOver + nCooked;
1018 spaceLeft = sinkPtr->size - sinkPtr->mark;
1019 if (spaceLeft >= needed) {
1020 spaceLeft = ExtendSinkBuffer(sinkPtr);
1021 }
1022 assert(spaceLeft > needed);
1023 /*
1024 * Replace the characters from the mark with the translated
1025 * characters.
1026 */
1027 srcPtr = cooked;
1028 endPtr = cooked + nCooked;
1029 destPtr = sinkPtr->byteArr + sinkPtr->mark;
1030 while (srcPtr < endPtr) {
1031 *destPtr++ = *srcPtr++;
1032 }
1033 /* Add the number of newly translated characters to the mark */
1034 sinkPtr->mark += nCooked;
1035
1036 srcPtr = leftover;
1037 endPtr = leftover + nLeftOver;
1038 while (srcPtr < endPtr) {
1039 *destPtr++ = *srcPtr++;
1040 }
1041 sinkPtr->fill = sinkPtr->mark + nLeftOver;
1042 #endif /* >= 8.1.0 */
1043 }
1044 #ifdef WIN32
1045 /*
1046 * Translate CRLF character sequences to LF characters. We have to
1047 * do this after converting the string to UTF from UNICODE.
1048 */
1049 if (sinkPtr->encoding != ENCODING_BINARY) {
1050 int count;
1051 unsigned char *destPtr;
1052
1053 destPtr = srcPtr = sinkPtr->byteArr + oldMark;
1054 endPtr = sinkPtr->byteArr + sinkPtr->fill;
1055 *endPtr = '\0';
1056 count = 0;
1057 for (endPtr--; srcPtr < endPtr; srcPtr++) {
1058 if ((*srcPtr == '\r') && (*(srcPtr + 1) == '\n')) {
1059 count++;
1060 continue; /* Skip the CR in CR/LF sequences. */
1061 }
1062 if (srcPtr != destPtr) {
1063 *destPtr = *srcPtr; /* Collapse the string, overwriting
1064 * the \r's encountered. */
1065 }
1066 destPtr++;
1067 }
1068 sinkPtr->mark -= count;
1069 sinkPtr->fill -= count;
1070 *destPtr = *srcPtr; /* Copy the last byte */
1071 if (*destPtr == '\r') {
1072 sinkPtr->mark--;
1073 }
1074 }
1075 #endif /* WIN32 */
1076 }
1077
1078 #ifdef WIN32
1079 /*
1080 *----------------------------------------------------------------------
1081 *
1082 * WaitProcess --
1083 *
1084 * Emulates the waitpid system call under the Win32 API.
1085 *
1086 * Results:
1087 * Returns 0 if the process is still alive, -1 on an error, or
1088 * the pid on a clean close.
1089 *
1090 * Side effects:
1091 * Unless WNOHANG is set and the wait times out, the process
1092 * information record will be deleted and the process handle
1093 * will be closed.
1094 *
1095 *----------------------------------------------------------------------
1096 */
1097 #define WINDEBUG 0
1098 static int
1099 WaitProcess(
1100 Process child,
1101 int *statusPtr,
1102 int flags)
1103 {
1104 int result;
1105 DWORD status, exitCode;
1106 int timeout;
1107
1108 #if WINDEBUG
1109 PurifyPrintf("WAITPID(%x)\n", child.hProcess);
1110 #endif
1111 *statusPtr = 0;
1112 if (child.hProcess == INVALID_HANDLE_VALUE) {
1113 errno = EINVAL;
1114 return -1;
1115 }
1116 #if WINDEBUG
1117 PurifyPrintf("WAITPID: waiting for 0x%x\n", child.hProcess);
1118 #endif
1119 timeout = (flags & WNOHANG) ? 0 : INFINITE;
1120 status = WaitForSingleObject(child.hProcess, timeout);
1121
1122 #if WINDEBUG
1123 PurifyPrintf("WAITPID: wait status is %d\n", status);
1124 #endif
1125 switch (status) {
1126 case WAIT_FAILED:
1127 errno = ECHILD;
1128 *statusPtr = ECHILD;
1129 result = -1;
1130 break;
1131
1132 case WAIT_TIMEOUT:
1133 if (timeout == 0) {
1134 return 0; /* Try again */
1135 }
1136 result = 0;
1137 break;
1138
1139 default:
1140 case WAIT_ABANDONED:
1141 case WAIT_OBJECT_0:
1142 GetExitCodeProcess(child.hProcess, &exitCode);
1143 *statusPtr = ((exitCode << 8) & 0xff00);
1144 #if WINDEBUG
1145 PurifyPrintf("WAITPID: exit code of %d is %d (%x)\n", child.hProcess,
1146 *statusPtr, exitCode);
1147 #endif
1148 result = child.pid;
1149 assert(result != -1);
1150 break;
1151 }
1152 CloseHandle(child.hProcess);
1153 return result;
1154 }
1155
1156 static BOOL CALLBACK
1157 EnumWindowsProc(HWND hWnd, LPARAM lParam)
1158 {
1159 DWORD pid = 0;
1160 Process *procPtr = (Process *)lParam;
1161
1162 GetWindowThreadProcessId(hWnd, &pid);
1163 if (pid == procPtr->pid) {
1164 PostMessage(hWnd, WM_CLOSE, 0, 0);
1165 }
1166 return TRUE;
1167 }
1168
1169 /*
1170 *----------------------------------------------------------------------
1171 *
1172 * KillProcess --
1173 *
1174 * Emulates the UNIX kill system call under Win32 API.
1175 *
1176 * Results:
1177 * Returns 0 if the process is killed, -1 on an error.
1178 *
1179 * Side effects:
1180 * Process is terminated.
1181 *
1182 *----------------------------------------------------------------------
1183 */
1184 static int
1185 KillProcess(Process proc, int signal)
1186 {
1187 DWORD status;
1188
1189 if ((proc.hProcess == NULL) || (proc.hProcess == INVALID_HANDLE_VALUE)) {
1190 errno = EINVAL;
1191 return -1;
1192 }
1193
1194 EnumWindows(EnumWindowsProc, (LPARAM)&proc);
1195
1196 /*
1197 * Wait on the handle. If it signals, great. If it times out,
1198 * then call TerminateProcess on it.
1199 *
1200 * On Windows 95/98 this also has the added benefit of stopping
1201 * KERNEL32.dll from dumping. The 2 second number is arbitrary.
1202 * (1 second seems to fail intermittently).
1203 */
1204 status = WaitForSingleObject(proc.hProcess, 2000);
1205 if (status == WAIT_OBJECT_0) {
1206 return 0;
1207 }
1208 if (!TerminateProcess(proc.hProcess, 1)) {
1209 #if WINDEBUG
1210 PurifyPrintf("can't terminate process (handle=%d): %s\n",
1211 proc.hProcess, Blt_LastError());
1212 #endif /* WINDEBUG */
1213 return -1;
1214 }
1215 return 0;
1216 }
1217
1218 #endif /* WIN32 */
1219
1220 #if (TCL_VERSION_NUMBER < _VERSION(8,1,0))
1221
1222 static void
1223 NotifyOnUpdate(bgPtr, interp, sinkPtr, data, nBytes)
1224 BackgroundInfo *bgPtr;
1225 Tcl_Interp *interp;
1226 Sink *sinkPtr;
1227 unsigned char *data;
1228 int nBytes;
1229 {
1230 char save;
1231
1232 #if WINDEBUG_0
1233 PurifyPrintf("read %s\n", data);
1234 #endif
1235 if (data[0] == '\0') {
1236 return;
1237 }
1238 save = data[nBytes];
1239 data[nBytes] = '\0';
1240 if (sinkPtr->echo) {
1241 Tcl_Channel channel;
1242
1243 channel = Tcl_GetStdChannel(TCL_STDERR);
1244 if (channel == NULL) {
1245 Tcl_AppendResult(interp, "can't get stderr channel", (char *)NULL);
1246 Tcl_BackgroundError(interp);
1247 sinkPtr->echo = FALSE;
1248 } else {
1249 Tcl_Write(channel, data, nBytes);
1250 if (save == '\n') {
1251 Tcl_Write(channel, "\n", 1);
1252 }
1253 Tcl_Flush(channel);
1254 }
1255 }
1256 if (sinkPtr->updateCmd != NULL) {
1257 Tcl_DString dString;
1258 int result;
1259 register char **p;
1260
1261 Tcl_DStringInit(&dString);
1262 for (p = sinkPtr->updateCmd; *p != NULL; p++) {
1263 Tcl_DStringAppendElement(&dString, *p);
1264 }
1265 Tcl_DStringAppendElement(&dString, data);
1266 result = Tcl_GlobalEval(interp, Tcl_DStringValue(&dString));
1267 Tcl_DStringFree(&dString);
1268 if (result != TCL_OK) {
1269 Tcl_BackgroundError(interp);
1270 }
1271 }
1272 if (sinkPtr->updateVar != NULL) {
1273 int flags;
1274 char *result;
1275
1276 flags = (bgPtr->varFlags | TCL_LEAVE_ERR_MSG);
1277 result = Tcl_SetVar(interp, sinkPtr->updateVar, data, flags);
1278 if (result == NULL) {
1279 Tcl_BackgroundError(interp);
1280 }
1281 }
1282 data[nBytes] = save;
1283 }
1284
1285 #else
1286
1287 static void
1288 NotifyOnUpdate(bgPtr, interp, sinkPtr, data, nBytes)
1289 BackgroundInfo *bgPtr;
1290 Tcl_Interp *interp;
1291 Sink *sinkPtr;
1292 unsigned char *data;
1293 int nBytes;
1294 {
1295 Tcl_Obj *objPtr;
1296
1297 #if WINDEBUG_0
1298 PurifyPrintf("read %s\n", data);
1299 #endif
1300 if ((nBytes == 0) || (data[0] == '\0')) {
1301 return;
1302 }
1303 if (sinkPtr->echo) {
1304 Tcl_Channel channel;
1305
1306 channel = Tcl_GetStdChannel(TCL_STDERR);
1307 if (channel == NULL) {
1308 Tcl_AppendResult(interp, "can't get stderr channel", (char *)NULL);
1309 Tcl_BackgroundError(interp);
1310 sinkPtr->echo = FALSE;
1311 } else {
1312 if (data[nBytes] == '\n') {
1313 objPtr = Tcl_NewByteArrayObj(data, nBytes + 1);
1314 } else {
1315 objPtr = Tcl_NewByteArrayObj(data, nBytes);
1316 }
1317 Tcl_WriteObj(channel, objPtr);
1318 Tcl_Flush(channel);
1319 }
1320 }
1321
1322 objPtr = Tcl_NewByteArrayObj(data, nBytes);
1323 Tcl_IncrRefCount(objPtr);
1324 if (sinkPtr->objv != NULL) {
1325 int result;
1326
1327 sinkPtr->objv[sinkPtr->objc - 1] = objPtr;
1328 result = Tcl_EvalObjv(interp, sinkPtr->objc, sinkPtr->objv, TCL_GLOBAL_ONLY);
1329 if (result != TCL_OK) {
1330 Tcl_BackgroundError(interp);
1331 }
1332 }
1333 if (sinkPtr->updateVar != NULL) {
1334 Tcl_Obj *result;
1335
1336 result = Tcl_SetVar2Ex(interp, sinkPtr->updateVar, NULL, objPtr,
1337 (bgPtr->varFlags | TCL_LEAVE_ERR_MSG));
1338 if (result == NULL) {
1339 Tcl_BackgroundError(interp);
1340 }
1341 }
1342 Tcl_DecrRefCount(objPtr);
1343 }
1344
1345 #endif /* < 8.1.0 */
1346
1347 static int
1348 CollectData(bgPtr, sinkPtr)
1349 BackgroundInfo *bgPtr;
1350 Sink *sinkPtr;
1351 {
1352 if ((bgPtr->detached) && (sinkPtr->doneVar == NULL) && (sinkPtr->command == NULL)) {
1353 ResetSink(sinkPtr);
1354 }
1355 ReadBytes(bgPtr, sinkPtr);
1356 CookSink(bgPtr->interp, sinkPtr);
1357 if ((sinkPtr->mark > sinkPtr->lastMark) &&
1358 (sinkPtr->flags & SINK_NOTIFY)) {
1359 unsigned char *data;
1360 int length;
1361
1362 if (sinkPtr->flags & SINK_BUFFERED) {
1363 /* For line-by-line updates, call NotifyOnUpdate for each
1364 * new complete line. */
1365 while ((data = NextLine(sinkPtr, &length)) != NULL) {
1366 NotifyOnUpdate(bgPtr, bgPtr->interp, sinkPtr, data, length);
1367 }
1368 } else {
1369 data = NextBlock(sinkPtr, &length);
1370 NotifyOnUpdate(bgPtr, bgPtr->interp, sinkPtr, data, length);
1371 }
1372 }
1373 if (bgPtr->maxBytes>0) {
1374 if (sinkPtr->mark >= bgPtr->maxBytes) {
1375 bgPtr->maxExceed = 1;
1376 return TCL_BREAK;
1377 }
1378 }
1379 if (sinkPtr->status >= 0) {
1380 return TCL_OK;
1381 }
1382 if (sinkPtr->status == READ_ERROR) {
1383 Tcl_AppendResult(bgPtr->interp, "can't read data from ", sinkPtr->name,
1384 ": ", Tcl_PosixError(bgPtr->interp), (char *)NULL);
1385 Tcl_BackgroundError(bgPtr->interp);
1386 return TCL_ERROR;
1387 }
1388 #if WINDEBUG
1389 PurifyPrintf("CollectData %s: done\n", sinkPtr->name);
1390 #endif
1391 return TCL_RETURN;
1392 }
1393
1394 /*
1395 *----------------------------------------------------------------------
1396 *
1397 * CreateSinkHandler --
1398 *
1399 * Creates a file handler for the given sink. The file
1400 * descriptor is also set for non-blocking I/O.
1401 *
1402 * Results:
1403 * None.
1404 *
1405 * Side effects:
1406 * The memory allocated to the BackgroundInfo structure released.
1407 *
1408 *----------------------------------------------------------------------
1409 */
1410 static int
1411 CreateSinkHandler(bgPtr, sinkPtr, proc)
1412 BackgroundInfo *bgPtr;
1413 Sink *sinkPtr;
1414 Tcl_FileProc *proc;
1415 {
1416 #ifndef WIN32
1417 int flags;
1418
1419 flags = fcntl(sinkPtr->fd, F_GETFL);
1420 #ifdef O_NONBLOCK
1421 flags |= O_NONBLOCK;
1422 #else
1423 flags |= O_NDELAY;
1424 #endif
1425 if (fcntl(sinkPtr->fd, F_SETFL, flags) < 0) {
1426 Tcl_AppendResult(bgPtr->interp, "can't set file descriptor ",
1427 Blt_Itoa(sinkPtr->fd), " to non-blocking:",
1428 Tcl_PosixError(bgPtr->interp), (char *)NULL);
1429 return TCL_ERROR;
1430 }
1431 #endif /* WIN32 */
1432 #ifdef FILEHANDLER_USES_TCLFILES
1433 sinkPtr->file = Tcl_GetFile((ClientData)sinkPtr->fd, TCL_UNIX_FD);
1434 Tcl_CreateFileHandler(sinkPtr->file, TCL_READABLE, proc, bgPtr);
1435 #else
1436 Tcl_CreateFileHandler(sinkPtr->fd, TCL_READABLE, proc, bgPtr);
1437 #endif /* FILEHANDLER_USES_TCLFILES */
1438 return TCL_OK;
1439 }
1440
1441 static void
1442 DisableTriggers(bgPtr)
1443 BackgroundInfo *bgPtr; /* Background info record. */
1444 {
1445 int k;
1446
1447 if (bgPtr->traced) {
1448 Tcl_UntraceVar(bgPtr->interp, bgPtr->statVar, TRACE_FLAGS,
1449 VariableProc, bgPtr);
1450 bgPtr->traced = FALSE;
1451 }
1452 if (IsOpenSink(&bgPtr->sink1)) {
1453 CloseSink(bgPtr, bgPtr->interp, &bgPtr->sink1);
1454 }
1455 if (IsOpenSink(&bgPtr->sink2)) {
1456 CloseSink(bgPtr, bgPtr->interp, &bgPtr->sink2);
1457 }
1458 for( k = 0 ; k < bgPtr->nTimers ; k++ ){
1459 Tcl_DeleteTimerHandler(bgPtr->timerTokens[k]);
1460 }
1461 bgPtr->nTimers = 0;
1462 if (bgPtr->donePtr != NULL) {
1463 *bgPtr->donePtr = TRUE;
1464 }
1465 }
1466
1467
1468 /*
1469 *----------------------------------------------------------------------
1470 *
1471 * FreeBackgroundInfo --
1472 *
1473 * Releases the memory allocated for the backgrounded process.
1474 *
1475 *----------------------------------------------------------------------
1476 */
1477 static void
1478 FreeBackgroundInfo(bgPtr)
1479 BackgroundInfo *bgPtr;
1480 {
1481 Blt_FreeSwitches(bgPtr->interp, switchSpecs, (char *)bgPtr, 0);
1482 if (bgPtr->statVar != NULL) {
1483 Blt_Free(bgPtr->statVar);
1484 }
1485 if (bgPtr->procArr != NULL) {
1486 Blt_Free(bgPtr->procArr);
1487 }
1488 if (bgPtr->timerTokens != NULL) {
1489 Blt_Free(bgPtr->timerTokens);
1490 }
1491 Blt_Free(bgPtr);
1492 }
1493
1494 /*
1495 *----------------------------------------------------------------------
1496 *
1497 * DestroyBackgroundInfo --
1498 *
1499 * This procedure is invoked by Tcl_EventuallyFree or Tcl_Release
1500 * to clean up the internal structure (BackgroundInfo) at a safe
1501 * time (when no one is using it anymore).
1502 *
1503 * Results:
1504 * None.b
1505 *
1506 * Side effects:
1507 * The memory allocated to the BackgroundInfo structure released.
1508 *
1509 *----------------------------------------------------------------------
1510 */
1511 /* ARGSUSED */
1512 static void
1513 DestroyBackgroundInfo(bgPtr)
1514 BackgroundInfo *bgPtr; /* Background info record. */
1515 {
1516 Tcl_DontCallWhenDeleted(bgPtr->interp, InterpDeleted, (ClientData)bgPtr);
1517 DisableTriggers(bgPtr);
1518 FreeSinkBuffer(&bgPtr->sink2);
1519 FreeSinkBuffer(&bgPtr->sink1);
1520 if (bgPtr->procArr != NULL) {
1521 register int i;
1522
1523 for (i = 0; i < bgPtr->nProcs; i++) {
1524 if (bgPtr->signalNum > 0) {
1525 kill(bgPtr->procArr[i], bgPtr->signalNum);
1526 }
1527 #ifdef WIN32
1528 Tcl_DetachPids(1, (Tcl_Pid *)&bgPtr->procArr[i].pid);
1529 #else
1530 #if (TCL_MAJOR_VERSION == 7)
1531 Tcl_DetachPids(1, &bgPtr->procArr[i]);
1532 #else
1533 Tcl_DetachPids(1, (Tcl_Pid *)&bgPtr->procArr[i]);
1534 #endif /* TCL_MAJOR_VERSION == 7 */
1535 #endif /* WIN32 */
1536 }
1537 }
1538 FreeBackgroundInfo(bgPtr);
1539 Tcl_ReapDetachedProcs();
1540 }
1541
1542 /*
1543 * ----------------------------------------------------------------------
1544 *
1545 * VariableProc --
1546 *
1547 * Kills all currently running subprocesses (given the specified
1548 * signal). This procedure is called when the user sets the status
1549 * variable associated with this group of child subprocesses.
1550 *
1551 * Results:
1552 * Always returns NULL. Only called from a variable trace.
1553 *
1554 * Side effects:
1555 * The subprocesses are signaled for termination using the
1556 * specified kill signal. Additionally, any resources allocated
1557 * to track the subprocesses is released.
1558 *
1559 * ----------------------------------------------------------------------
1560 */
1561 /* ARGSUSED */
1562 static char *
1563 VariableProc(
1564 ClientData clientData, /* File output information. */
1565 Tcl_Interp *interp,
1566 char *part1,
1567 char *part2, /* Not Used. */
1568 int flags)
1569 {
1570 if (flags & TRACE_FLAGS) {
1571 BackgroundInfo *bgPtr = clientData;
1572
1573 /* Kill all child processes that remain alive. */
1574 if ((bgPtr->procArr != NULL) && (bgPtr->signalNum > 0)) {
1575 register int i;
1576
1577 for (i = 0; i < bgPtr->nProcs; i++) {
1578 kill(bgPtr->procArr[i], bgPtr->signalNum);
1579 }
1580 if (bgPtr->closeKill>0 && bgPtr->nProcs>0) {
1581 bgPtr->cKilled = 1;
1582 AddTimerHandler( bgPtr, bgPtr->closeKill ) ;
1583 }
1584 }
1585 }
1586 return NULL;
1587 }
1588
1589 /*
1590 *----------------------------------------------------------------------
1591 *
1592 * TimerProc --
1593 *
1594 * This is a timer handler procedure which gets called
1595 * periodically to reap any of the sub-processes if they have
1596 * terminated. After the last process has terminated, the
1597 * contents of standard output are stored
1598 * in the output variable, which triggers the cleanup proc (using
1599 * a variable trace). The status the last process to exit is
1600 * written to the status variable.
1601 *
1602 * Results:
1603 * None. Called from the Tcl event loop.
1604 *
1605 * Side effects:
1606 * Many. The contents of procArr is shifted, leaving only those
1607 * sub-processes which have not yet terminated. If there are
1608 * still subprocesses left, this procedure is placed in the timer
1609 * queue again. Otherwise the output and possibly the status
1610 * variables are updated. The former triggers the cleanup
1611 * routine which will destroy the information and resources
1612 * associated with these background processes.
1613 *
1614 *----------------------------------------------------------------------
1615 */
1616 static void
1617 TimerProc(clientData)
1618 ClientData clientData;
1619 {
1620 BackgroundInfo *bgPtr = clientData;
1621 register int i;
1622 unsigned int lastPid;
1623 int pid;
1624 enum PROCESS_STATUS {
1625 PROCESS_EXITED, PROCESS_STOPPED, PROCESS_KILLED, PROCESS_UNKNOWN,
1626 PROCESS_MAX
1627 } pcode;
1628 WAIT_STATUS_TYPE waitStatus, lastStatus;
1629 int nLeft; /* Number of processes still not reaped */
1630 char string[200];
1631 Tcl_DString dString;
1632 int code;
1633 CONST char *result;
1634
1635 lastPid = (unsigned int)-1;
1636 *((int *)&waitStatus) = 0;
1637 *((int *)&lastStatus) = 0;
1638
1639 nLeft = 0;
1640 for (i = 0; i < bgPtr->nProcs; i++) {
1641 #ifdef WIN32
1642 pid = WaitProcess(bgPtr->procArr[i], (int *)&waitStatus, WNOHANG);
1643 #else
1644 pid = waitpid(bgPtr->procArr[i], (int *)&waitStatus, WNOHANG);
1645 #endif
1646 if (pid == 0) { /* Process has not terminated yet */
1647 if (nLeft < i) {
1648 bgPtr->procArr[nLeft] = bgPtr->procArr[i];
1649 }
1650 nLeft++; /* Count the number of processes left */
1651 } else if (pid != -1) {
1652 /*
1653 * Save the status information associated with the subprocess.
1654 * We'll use it only if this is the last subprocess to be reaped.
1655 */
1656 lastStatus = waitStatus;
1657 lastPid = (unsigned int)pid;
1658 }
1659 }
1660 bgPtr->nProcs = nLeft;
1661
1662 if ((nLeft > 0) || (IsOpenSink(&bgPtr->sink1)) ||
1663 (IsOpenSink(&bgPtr->sink2))) {
1664 /* Keep polling for the status of the children that are left */
1665 if (bgPtr->closeKill>0 && bgPtr->cKilled) {
1666 if (IsOpenSink(&bgPtr->sink1)) {
1667 CloseSink(bgPtr, bgPtr->interp, &bgPtr->sink1);
1668 }
1669 if (IsOpenSink(&bgPtr->sink2)) {
1670 CloseSink(bgPtr, bgPtr->interp, &bgPtr->sink2);
1671 }
1672 }
1673 AddTimerHandler( bgPtr, bgPtr->interval ) ;
1674 #if WINDEBUG
1675 PurifyPrintf("schedule TimerProc(nProcs=%d)\n", nLeft);
1676 #endif
1677 return;
1678 }
1679
1680 /*
1681 * All child processes have completed. Set the status variable
1682 * with the status of the last process reaped. The status is a
1683 * list of an error token, the exit status, and a message.
1684 */
1685
1686 code = WEXITSTATUS(lastStatus);
1687 Tcl_DStringInit(&dString);
1688 if (bgPtr->maxExceed) {
1689 Tcl_DStringAppendElement(&dString, "MAXBYTES");
1690 pcode = PROCESS_MAX;
1691 } else if (WIFEXITED(lastStatus)) {
1692 Tcl_DStringAppendElement(&dString, "EXITED");
1693 pcode = PROCESS_EXITED;
1694 } else if (WIFSIGNALED(lastStatus)) {
1695 Tcl_DStringAppendElement(&dString, "KILLED");
1696 pcode = PROCESS_KILLED;
1697 code = -1;
1698 } else if (WIFSTOPPED(lastStatus)) {
1699 Tcl_DStringAppendElement(&dString, "STOPPED");
1700 pcode = PROCESS_STOPPED;
1701 code = -1;
1702 } else {
1703 Tcl_DStringAppendElement(&dString, "UNKNOWN");
1704 pcode = PROCESS_UNKNOWN;
1705 }
1706 #ifdef WIN32
1707 sprintf(string, "%u", lastPid);
1708 Tcl_DStringAppendElement(&dString, string);
1709 #else
1710 Tcl_DStringAppendElement(&dString, Blt_Itoa(lastPid));
1711 #endif
1712 Tcl_DStringAppendElement(&dString, Blt_Itoa(code));
1713 switch(pcode) {
1714 case PROCESS_MAX:
1715 Tcl_DStringAppendElement(&dString, "max bytes exceeded");
1716 break;
1717 case PROCESS_EXITED:
1718 if (bgPtr->cKilled) {
1719 Tcl_DStringAppendElement(&dString, "kill signal");
1720 } else {
1721 Tcl_DStringAppendElement(&dString, "child completed normally");
1722 }
1723 break;
1724 case PROCESS_KILLED:
1725 Tcl_DStringAppendElement(&dString,
1726 Tcl_SignalMsg((int)(WTERMSIG(lastStatus))));
1727 break;
1728 case PROCESS_STOPPED:
1729 Tcl_DStringAppendElement(&dString,
1730 Tcl_SignalMsg((int)(WSTOPSIG(lastStatus))));
1731 break;
1732 case PROCESS_UNKNOWN:
1733 sprintf(string, "child completed with unknown status 0x%x",
1734 *((int *)&lastStatus));
1735 Tcl_DStringAppendElement(&dString, string);
1736 break;
1737 }
1738 if (bgPtr->exitCodePtr != NULL) {
1739 *bgPtr->exitCodePtr = code;
1740 }
1741 DisableTriggers(bgPtr);
1742 result = Tcl_SetVar(bgPtr->interp, bgPtr->statVar,
1743 Tcl_DStringValue(&dString), bgPtr->varFlags | TCL_LEAVE_ERR_MSG);
1744 SinkCallback(bgPtr->interp, &bgPtr->sink1, Tcl_DStringValue(&dString));
1745 Tcl_DStringFree(&dString);
1746 if (result == NULL) {
1747 Tcl_BackgroundError(bgPtr->interp);
1748 }
1749 if (bgPtr->detached) {
1750 DestroyBackgroundInfo(bgPtr);
1751 }
1752 }
1753
1754 /*
1755 *----------------------------------------------------------------------
1756 *
1757 * Stdoutproc --
1758 *
1759 * This procedure is called when output from the detached pipeline
1760 * is available. The output is read and saved in a buffer in the
1761 * BackgroundInfo structure.
1762 *
1763 * Results:
1764 * None.
1765 *
1766 * Side effects:
1767 * Data is stored in the buffer. This character array may
1768 * be increased as more space is required to contain the output
1769 * of the pipeline.
1770 *
1771 *----------------------------------------------------------------------
1772 */
1773 /* ARGSUSED */
1774 static void
1775 StdoutProc(clientData, mask)
1776 ClientData clientData; /* File output information. */
1777 int mask; /* Not used. */
1778 {
1779 BackgroundInfo *bgPtr = clientData;
1780
1781 if (CollectData(bgPtr, &bgPtr->sink1) == TCL_OK) {
1782 return;
1783 }
1784 /*
1785 * Either EOF or an error has occurred. In either case, close the
1786 * sink. Note that closing the sink will also remove the file
1787 * handler, so this routine will not be called again.
1788 */
1789 CloseSink(bgPtr, bgPtr->interp, &bgPtr->sink1);
1790
1791 /*
1792 * If both sinks (stdout and stderr) are closed, this doesn't
1793 * necessarily mean that the process has terminated. Set up a
1794 * timer handler to periodically poll for the exit status of each
1795 * process. Initially check at the next idle interval.
1796 */
1797 if (!IsOpenSink(&bgPtr->sink2)) {
1798 AddTimerHandler( bgPtr, 0 ) ;
1799 }
1800 }
1801
1802 /*
1803 *----------------------------------------------------------------------
1804 *
1805 * StderrProc --
1806 *
1807 * This procedure is called when error from the detached pipeline
1808 * is available. The error is read and saved in a buffer in the
1809 * BackgroundInfo structure.
1810 *
1811 * Results:
1812 * None.
1813 *
1814 * Side effects:
1815 * Data is stored in the buffer. This character array may
1816 * be increased as more space is required to contain the stderr
1817 * of the pipeline.
1818 *
1819 *----------------------------------------------------------------------
1820 */
1821 /* ARGSUSED */
1822 static void
1823 StderrProc(clientData, mask)
1824 ClientData clientData; /* File output information. */
1825 int mask; /* Not used. */
1826 {
1827 BackgroundInfo *bgPtr = clientData;
1828
1829 if (CollectData(bgPtr, &bgPtr->sink2) == TCL_OK) {
1830 return;
1831 }
1832 /*
1833 * Either EOF or an error has occurred. In either case, close the
1834 * sink. Note that closing the sink will also remove the file
1835 * handler, so this routine will not be called again.
1836 */
1837 CloseSink(bgPtr, bgPtr->interp, &bgPtr->sink2);
1838
1839 /*
1840 * If both sinks (stdout and stderr) are closed, this doesn't
1841 * necessarily mean that the process has terminated. Set up a
1842 * timer handler to periodically poll for the exit status of each
1843 * process. Initially check at the next idle interval.
1844 */
1845 if (!IsOpenSink(&bgPtr->sink1)) {
1846 AddTimerHandler( bgPtr, 0 ) ;
1847 }
1848 }
1849
1850 static void
1851 AddTimerHandler( bgPtr, interval )
1852 BackgroundInfo *bgPtr;
1853 int interval;
1854 {
1855 if(!(bgPtr->timerTokens)){
1856 bgPtr->timerTokens = Blt_Calloc(EXPECTED_NUM_TIMERS, sizeof(Tcl_TimerToken *));
1857 }
1858 if( ++bgPtr->nTimers >= EXPECTED_NUM_TIMERS ){
1859 bgPtr->timerTokens = Blt_Realloc( bgPtr->timerTokens,
1860 bgPtr->nTimers * sizeof(Tcl_TimerToken *) ) ;
1861 }
1862 bgPtr->timerTokens[bgPtr->nTimers-1] = Tcl_CreateTimerHandler(interval,
1863 TimerProc,
1864 bgPtr);
1865 }
1866
1867 static void
1868 InterpDeleted(clientData, interp)
1869 ClientData clientData; /* Thread-specific data. */
1870 Tcl_Interp *interp; /* Current interpreter. */
1871 {
1872 BackgroundInfo *bgPtr = (BackgroundInfo *)clientData;
1873 DestroyBackgroundInfo(bgPtr);
1874 }
1875
1876 void
1877 MakeLocal( char *ns, char **str) {
1878 Tcl_DString dStr;
1879 if (ns == NULL) return;
1880 if (!strcmp(ns,"::")) return;
1881 if (!strncmp(*str,"::",2)) return;
1882 Tcl_DStringInit(&dStr);
1883 Tcl_DStringAppend(&dStr, ns, -1);
1884 Tcl_DStringAppend(&dStr, "::", -1);
1885 Tcl_DStringAppend(&dStr, *str, -1);
1886 Blt_Free(*str);
1887 *str = Blt_Strdup( Tcl_DStringValue(&dStr) );
1888 Tcl_DStringFree(&dStr);
1889 }
1890 /*
1891 *----------------------------------------------------------------------
1892 *
1893 * BgexecCmd --
1894 *
1895 * This procedure is invoked to process the "bgexec" Tcl command.
1896 * See the user documentation for details on what it does.
1897 *
1898 * Results:
1899 * A standard Tcl result.
1900 *
1901 * Side effects:
1902 * See the user documentation.
1903 *
1904 *----------------------------------------------------------------------
1905 */
1906 /* ARGSUSED */
1907 static int
1908 BgexecCmd(clientData, interp, argc, argv)
1909 ClientData clientData; /* Thread-specific data. */
1910 Tcl_Interp *interp; /* Current interpreter. */
1911 int argc; /* Number of arguments. */
1912 char **argv; /* Argument strings. */
1913 {
1914 int *outFdPtr, *errFdPtr;
1915 int nProcs;
1916 Process *pidPtr;
1917 char *lastArg;
1918 BackgroundInfo *bgPtr;
1919 int i, term = 0, tail = 0;
1920 int detached;
1921 Tcl_Encoding encoding;
1922
1923 if (argc < 3) {
1924 Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
1925 " varName ?options? command ?arg...?\"", (char *)NULL);
1926 return TCL_ERROR;
1927 }
1928
1929 /* Check if the command line is to be run detached (the last
1930 * argument is "&") */
1931 lastArg = argv[argc - 1];
1932 detached = ((lastArg[0] == '&') && (lastArg[1] == '\0'));
1933 if (detached) {
1934 argc--;
1935 argv[argc] = NULL; /* Remove the '&' argument */
1936 }
1937 bgPtr = Blt_Calloc(1, sizeof(BackgroundInfo));
1938 assert(bgPtr);
1939
1940 /* Initialize the background information record */
1941 bgPtr->interp = interp;
1942 bgPtr->signalNum = SIGKILL;
1943 bgPtr->nProcs = -1;
1944 bgPtr->interval = 1000;
1945 bgPtr->detached = detached;
1946 bgPtr->keepNewline = TRUE;
1947 bgPtr->statVar = Blt_Strdup(argv[1]);
1948 bgPtr->timerTokens = NULL;
1949 bgPtr->nTimers = 0;
1950 bgPtr->closeKill = 0;
1951
1952 /* Try to clean up any detached processes */
1953 Tcl_ReapDetachedProcs();
1954
1955 for (i=2; i<argc; i += 2) {
1956 if (!strcmp(argv[i],"--")) {
1957 term = i+1;
1958 tail = (argc-i);
1959 break;
1960 }
1961 }
1962 i = Blt_ProcessSwitches(interp, switchSpecs, argc - 2 - tail, argv + 2,
1963 (char *)bgPtr, BLT_SWITCH_ARGV_PARTIAL);
1964 if (i < 0) {
1965 FreeBackgroundInfo(bgPtr);
1966 return TCL_ERROR;
1967 }
1968 bgPtr->varFlags = TCL_GLOBAL_ONLY;
1969 if (bgPtr->localVars) {
1970 if (detached) {
1971 bgPtr->varFlags = TCL_NAMESPACE_ONLY;
1972 } else {
1973 bgPtr->varFlags = 0;
1974 }
1975 }
1976 if (term) {
1977 i = term;
1978 } else {
1979 i += 2;
1980 }
1981 /* Must be at least one argument left as the command to execute. */
1982 if (argc <= i) {
1983 Tcl_AppendResult(interp, "missing command to execute: should be \"",
1984 argv[0], " varName ?options? command ?arg...?\"", (char *)NULL);
1985 FreeBackgroundInfo(bgPtr);
1986 return TCL_ERROR;
1987 }
1988
1989 if (bgPtr->localVars && (detached)) {
1990 char *ns = NULL;
1991 Tcl_Namespace *nsPtr;
1992 nsPtr = Tcl_GetCurrentNamespace(interp);
1993
1994 if (nsPtr != NULL) {
1995 ns = nsPtr->fullName;
1996 }
1997 if (bgPtr->statVar) MakeLocal(ns, &bgPtr->statVar);
1998 if (bgPtr->sink1.doneVar) MakeLocal(ns, &bgPtr->sink1.doneVar);
1999 if (bgPtr->sink1.command) MakeLocal(ns, &bgPtr->sink1.command);
2000 if (bgPtr->sink1.updateVar) MakeLocal(ns, &bgPtr->sink1.updateVar);
2001 if (bgPtr->sink2.doneVar) MakeLocal(ns, &bgPtr->sink2.doneVar);
2002 if (bgPtr->sink2.command) MakeLocal(ns, &bgPtr->sink2.command);
2003 if (bgPtr->sink2.updateVar) MakeLocal(ns, &bgPtr->sink2.updateVar);
2004 }
2005
2006 /* Put a trace on the exit status variable. The will also allow
2007 * the user to prematurely terminate the pipeline by simply
2008 * setting it. */
2009 if (Tcl_TraceVar(interp, bgPtr->statVar, TRACE_FLAGS, VariableProc, bgPtr) != TCL_OK) {
2010 FreeBackgroundInfo(bgPtr);
2011 return TCL_ERROR;
2012 }
2013 bgPtr->traced = TRUE;
2014
2015 encoding = ENCODING_ASCII;
2016 if (bgPtr->outputEncodingName != NULL) {
2017 if (strcmp(bgPtr->outputEncodingName, "binary") == 0) {
2018 encoding = ENCODING_BINARY;
2019 } else {
2020 #if (TCL_VERSION_NUMBER >= _VERSION(8,1,0))
2021 encoding = Tcl_GetEncoding(interp, bgPtr->outputEncodingName);
2022 if (encoding == NULL) {
2023 goto error;
2024 }
2025 #endif
2026 }
2027 }
2028 InitSink(bgPtr, &bgPtr->sink1, "stdout", encoding);
2029 if (bgPtr->errorEncodingName != NULL) {
2030 if (strcmp(bgPtr->errorEncodingName, "binary") == 0) {
2031 encoding = ENCODING_BINARY;
2032 } else {
2033 #if (TCL_VERSION_NUMBER >= _VERSION(8,1,0))
2034 encoding = Tcl_GetEncoding(interp, bgPtr->errorEncodingName);
2035 if (encoding == NULL) {
2036 goto error;
2037 }
2038 #endif
2039 }
2040 }
2041 InitSink(bgPtr, &bgPtr->sink2, "stderr", encoding);
2042
2043 outFdPtr = errFdPtr = (int *)NULL;
2044 #ifdef WIN32
2045 if ((!bgPtr->detached) ||
2046 (bgPtr->sink1.doneVar != NULL) ||
2047 (bgPtr->sink1.command != NULL) ||
2048 (bgPtr->sink1.updateVar != NULL) ||
2049 (bgPtr->sink1.updateCmd != NULL)) {
2050 outFdPtr = &bgPtr->sink1.fd;
2051 }
2052 #else
2053 outFdPtr = &bgPtr->sink1.fd;
2054 #endif
2055 if ((bgPtr->sink2.doneVar != NULL) ||
2056 (bgPtr->sink2.updateVar != NULL) ||
2057 (bgPtr->sink2.updateCmd != NULL) ||
2058 (bgPtr->sink2.echo)) {
2059 errFdPtr = &bgPtr->sink2.fd;
2060 }
2061 nProcs = Blt_CreatePipeline(interp, argc - i, argv + i, &pidPtr,
2062 (int *)NULL, outFdPtr, errFdPtr);
2063 if (nProcs < 0) {
2064 goto error;
2065 }
2066 bgPtr->procArr = pidPtr;
2067 bgPtr->nProcs = nProcs;
2068
2069 if (bgPtr->sink1.fd == -1) {
2070
2071 /* If output has been redirected, start polling immediately
2072 * for the exit status of each process. Normally, this is
2073 * done only after stdout has been closed by the last process,
2074 * but here stdout has been redirected. The default polling
2075 * interval is every 1 second. */
2076
2077 AddTimerHandler( bgPtr, bgPtr->interval ) ;
2078
2079 } else if (CreateSinkHandler(bgPtr, &bgPtr->sink1, StdoutProc) != TCL_OK) {
2080 goto error;
2081 }
2082 if ((bgPtr->sink2.fd != -1) &&
2083 (CreateSinkHandler(bgPtr, &bgPtr->sink2, StderrProc) != TCL_OK)) {
2084 goto error;
2085 }
2086 Tcl_CallWhenDeleted(interp, InterpDeleted, (ClientData)bgPtr);
2087 if (bgPtr->detached) {
2088 char string[200];
2089
2090 /* If detached, return a list of the child process ids instead
2091 * of the output of the pipeline. */
2092 for (i = 0; i < nProcs; i++) {
2093 #ifdef WIN32
2094 sprintf(string, "%u", (unsigned int)bgPtr->procArr[i].pid);
2095 #else
2096 sprintf(string, "%d", bgPtr->procArr[i]);
2097 #endif
2098 Tcl_AppendElement(interp, string);
2099 }
2100 } else {
2101 int exitCode;
2102 int done, doRaise;
2103
2104 bgPtr->exitCodePtr = &exitCode;
2105 bgPtr->donePtr = &done;
2106
2107 exitCode = done = 0;
2108 while (!done) {
2109 Tcl_DoOneEvent(0);
2110 }
2111 DisableTriggers(bgPtr);
2112 if ((exitCode == 0 || bgPtr->doRaise==0) && (bgPtr->sink1.doneVar == NULL) && (bgPtr->sink1.command == NULL)) {
2113 unsigned char *data;
2114 size_t length;
2115
2116 /* Return the output of the pipeline. */
2117 GetSinkData(&bgPtr->sink1, &data, &length);
2118 #if (TCL_VERSION_NUMBER < _VERSION(8,1,0))
2119 data[length] = '\0';
2120 Tcl_SetResult(interp, data, TCL_VOLATILE);
2121 #else
2122 Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(data, length));
2123 #endif
2124 }
2125 /* Clean up resources used. */
2126 doRaise = bgPtr->doRaise;
2127 DestroyBackgroundInfo(bgPtr);
2128 if ((doRaise) && exitCode != 0) {
2129 Tcl_AppendResult(interp, "child process exited abnormally",
2130 (char *)NULL);
2131 return TCL_ERROR;
2132 }
2133 }
2134 return TCL_OK;
2135 error:
2136 DisableTriggers(bgPtr);
2137 DestroyBackgroundInfo(bgPtr);
2138 return TCL_ERROR;
2139 }
2140
2141
2142 static int
2143 KillCmd(clientData, interp, argc, argv)
2144 ClientData clientData; /* Thread-specific data. */
2145 Tcl_Interp *interp; /* Current interpreter. */
2146 int argc; /* Number of arguments. */
2147 char **argv; /* Argument strings. */
2148 {
2149 char *string;
2150 int signalNum = SIGKILL;
2151 int pid;
2152 #ifdef WIN32
2153 HANDLE h;
2154 #endif
2155
2156 if (argc>3) {
2157 Tcl_AppendResult(interp, "too many args", 0);
2158 return TCL_ERROR;
2159 }
2160 if (argc<2) {
2161 Tcl_AppendResult(interp, "pid required", 0);
2162 return TCL_ERROR;
2163 }
2164 if (Tcl_GetInt(interp, argv[1], &pid) != TCL_OK) {
2165 return TCL_ERROR;
2166 }
2167
2168 #ifdef WIN32
2169 if (argc!=2) {
2170 Tcl_AppendResult(interp, "windows does not support signo", 0);
2171 return TCL_ERROR;
2172 }
2173 if (!(h = OpenProcess (PROCESS_TERMINATE, 0, pid))) {
2174 Tcl_AppendResult (interp, "invalid pid or access", NULL);
2175 return TCL_ERROR;
2176 }
2177
2178 if (TerminateProcess (h, 1) == 0) {
2179 Tcl_AppendResult (interp, "TerminateProcess failure", NULL);
2180 return TCL_ERROR;
2181 }
2182
2183 CloseHandle (h);
2184 #else
2185 if (argc==3) {
2186 string = argv[2];
2187 if (isdigit(UCHAR(string[0]))) {
2188 if (Tcl_GetInt(interp, string, &signalNum) != TCL_OK) {
2189 return TCL_ERROR;
2190 }
2191 } else {
2192 char *name;
2193 register SignalId *sigPtr;
2194
2195 name = string;
2196
2197 /* Clip off any "SIG" prefix from the signal name */
2198 if ((name[0] == 'S') && (name[1] == 'I') && (name[2] == 'G')) {
2199 name += 3;
2200 }
2201 signalNum = -1;
2202 for (sigPtr = signalIds; sigPtr->number > 0; sigPtr++) {
2203 if (strcmp(sigPtr->name + 3, name) == 0) {
2204 signalNum = sigPtr->number;
2205 break;
2206 }
2207 }
2208 if (signalNum < 0) {
2209 Tcl_AppendResult(interp, "unknown signal \"", string, "\"",
2210 (char *)NULL);
2211 return TCL_ERROR;
2212 }
2213 }
2214 if ((signalNum < 0) || (signalNum > NSIG)) {
2215 /* Outside range of signals */
2216 Tcl_AppendResult(interp, "signal number \"", string,
2217 "\" is out of range", (char *)NULL);
2218 return TCL_ERROR;
2219 }
2220 }
2221 kill(pid, signalNum);
2222 #endif
2223 return TCL_OK;
2224 }
2225
2226 /*
2227 *----------------------------------------------------------------------
2228 *
2229 * Blt_BgexecInit --
2230 *
2231 * This procedure is invoked to initialize the "bgexec" Tcl
2232 * command. See the user documentation for details on what it
2233 * does.
2234 *
2235 * Results:
2236 * None.
2237 *
2238 * Side effects:
2239 * See the user documentation.
2240 *
2241 *----------------------------------------------------------------------
2242 */
2243 int
2244 Blt_BgexecInit(interp)
2245 Tcl_Interp *interp;
2246 {
2247 static Blt_CmdSpec cmdSpec = {"bgexec", BgexecCmd, };
2248 static Blt_CmdSpec cmdSpec2 = {"kill", KillCmd, };
2249
2250 if (Blt_InitCmd(interp, "blt", &cmdSpec) == NULL) {
2251 return TCL_ERROR;
2252 }
2253 if (Blt_InitCmd(interp, "blt", &cmdSpec2) == NULL) {
2254 return TCL_ERROR;
2255 }
2256 return TCL_OK;
2257 }
2258 #endif /* NO_BGEXEC */