2 * (c) 2008 Steve Bennett <steveb@workware.net.au>
4 * Implements the exec command for Jim
6 * Based on code originally from Tcl 6.7 by John Ousterhout.
9 * The Tcl_Fork and Tcl_WaitPids procedures are based on code
10 * contributed by Karl Lehenbauer, Mark Diekhans and Peter
13 * Copyright 1987-1991 Regents of the University of California
14 * Permission to use, copy, modify, and distribute this
15 * software and its documentation for any purpose and without
16 * fee is hereby granted, provided that the above copyright
17 * notice appear in all copies. The University of California
18 * makes no representations about the suitability of this
19 * software for any purpose. It is provided "as is" without
20 * express or implied warranty.
26 #include "jimautoconf.h"
29 #if (!defined(HAVE_VFORK) || !defined(HAVE_WAITPID)) && !defined(__MINGW32__)
30 /* Poor man's implementation of exec with system()
31 * The system() call *may* do command line redirection, etc.
32 * The standard output is not available.
33 * Can't redirect filehandles.
35 static int Jim_ExecCmd(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
37 Jim_Obj
*cmdlineObj
= Jim_NewEmptyStringObj(interp
);
41 /* Create a quoted command line */
42 for (i
= 1; i
< argc
; i
++) {
44 const char *arg
= Jim_GetString(argv
[i
], &len
);
47 Jim_AppendString(interp
, cmdlineObj
, " ", 1);
49 if (strpbrk(arg
, "\\\" ") == NULL
) {
50 /* No quoting required */
51 Jim_AppendString(interp
, cmdlineObj
, arg
, len
);
55 Jim_AppendString(interp
, cmdlineObj
, "\"", 1);
56 for (j
= 0; j
< len
; j
++) {
57 if (arg
[j
] == '\\' || arg
[j
] == '"') {
58 Jim_AppendString(interp
, cmdlineObj
, "\\", 1);
60 Jim_AppendString(interp
, cmdlineObj
, &arg
[j
], 1);
62 Jim_AppendString(interp
, cmdlineObj
, "\"", 1);
64 rc
= system(Jim_String(cmdlineObj
));
66 Jim_FreeNewObj(interp
, cmdlineObj
);
69 Jim_Obj
*errorCode
= Jim_NewListObj(interp
, NULL
, 0);
70 Jim_ListAppendElement(interp
, errorCode
, Jim_NewStringObj(interp
, "CHILDSTATUS", -1));
71 Jim_ListAppendElement(interp
, errorCode
, Jim_NewIntObj(interp
, 0));
72 Jim_ListAppendElement(interp
, errorCode
, Jim_NewIntObj(interp
, rc
));
73 Jim_SetGlobalVariableStr(interp
, "errorCode", errorCode
);
80 int Jim_execInit(Jim_Interp
*interp
)
82 if (Jim_PackageProvide(interp
, "exec", "1.0", JIM_ERRMSG
))
84 Jim_CreateCommand(interp
, "exec", Jim_ExecCmd
, NULL
, NULL
);
88 /* Full exec implementation for unix and mingw */
93 #if defined(__MINGW32__)
94 /* XXX: Should we use this implementation for cygwin too? msvc? */
98 #define WIN32_LEAN_AND_MEAN
102 typedef HANDLE fdtype
;
103 typedef HANDLE pidtype
;
104 #define JIM_BAD_FD INVALID_HANDLE_VALUE
105 #define JIM_BAD_PID INVALID_HANDLE_VALUE
106 #define JimCloseFd CloseHandle
108 #define WIFEXITED(STATUS) 1
109 #define WEXITSTATUS(STATUS) (STATUS)
110 #define WIFSIGNALED(STATUS) 0
111 #define WTERMSIG(STATUS) 0
114 static fdtype
JimFileno(FILE *fh
);
115 static pidtype
JimWaitPid(pidtype pid
, int *status
, int nohang
);
116 static fdtype
JimDupFd(fdtype infd
);
117 static fdtype
JimOpenForRead(const char *filename
);
118 static FILE *JimFdOpenForRead(fdtype fd
);
119 static int JimPipe(fdtype pipefd
[2]);
120 static pidtype
JimStartWinProcess(Jim_Interp
*interp
, char **argv
, char *env
,
121 fdtype inputId
, fdtype outputId
, fdtype errorId
);
122 static int JimErrno(void);
124 #include "jim-signal.h"
127 #include <sys/wait.h>
132 #define JimErrno() errno
133 #define JIM_BAD_FD -1
134 #define JIM_BAD_PID -1
135 #define JimFileno fileno
136 #define JimReadFd read
137 #define JimCloseFd close
138 #define JimWaitPid waitpid
140 #define JimFdOpenForRead(FD) fdopen((FD), "r")
141 #define JimOpenForRead(NAME) open((NAME), O_RDONLY, 0)
144 static const char *JimStrError(void);
145 static char **JimSaveEnv(char **env
);
146 static void JimRestoreEnv(char **env
);
147 static int JimCreatePipeline(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
,
148 pidtype
**pidArrayPtr
, fdtype
*inPipePtr
, fdtype
*outPipePtr
, fdtype
*errFilePtr
);
149 static void JimDetachPids(Jim_Interp
*interp
, int numPids
, const pidtype
*pidPtr
);
150 static int JimCleanupChildren(Jim_Interp
*interp
, int numPids
, pidtype
*pidPtr
, fdtype errorId
);
151 static fdtype
JimCreateTemp(Jim_Interp
*interp
, const char *contents
);
152 static fdtype
JimOpenForWrite(const char *filename
, int append
);
153 static int JimRewindFd(fdtype fd
);
155 static void Jim_SetResultErrno(Jim_Interp
*interp
, const char *msg
)
157 Jim_SetResultFormatted(interp
, "%s: %s", msg
, JimStrError());
160 static const char *JimStrError(void)
162 return strerror(JimErrno());
165 static void Jim_RemoveTrailingNewline(Jim_Obj
*objPtr
)
168 const char *s
= Jim_GetString(objPtr
, &len
);
170 if (len
> 0 && s
[len
- 1] == '\n') {
172 objPtr
->bytes
[objPtr
->length
] = '\0';
177 * Read from 'fd', append the data to strObj and close 'fd'.
178 * Returns JIM_OK if OK, or JIM_ERR on error.
180 static int JimAppendStreamToString(Jim_Interp
*interp
, fdtype fd
, Jim_Obj
*strObj
)
183 FILE *fh
= JimFdOpenForRead(fd
);
189 int retval
= fread(buf
, 1, sizeof(buf
), fh
);
191 Jim_AppendString(interp
, strObj
, buf
, retval
);
193 if (retval
!= sizeof(buf
)) {
197 Jim_RemoveTrailingNewline(strObj
);
203 * If the last character of the result is a newline, then remove
204 * the newline character (the newline would just confuse things).
206 * Note: Ideally we could do this by just reducing the length of stringrep
207 * by 1, but there is no API for this :-(
209 static void JimTrimTrailingNewline(Jim_Interp
*interp
)
212 const char *p
= Jim_GetString(Jim_GetResult(interp
), &len
);
214 if (len
> 0 && p
[len
- 1] == '\n') {
215 Jim_SetResultString(interp
, p
, len
- 1);
220 * Builds the environment array from $::env
222 * If $::env is not set, simply returns environ.
224 * Otherwise allocates the environ array from the contents of $::env
226 * If the exec fails, memory can be freed via JimFreeEnv()
228 static char **JimBuildEnv(Jim_Interp
*interp
)
230 #if defined(jim_ext_tclcompat)
238 Jim_Obj
*objPtr
= Jim_GetGlobalVariableStr(interp
, "env", JIM_NONE
);
241 return Jim_GetEnviron();
244 /* We build the array as a single block consisting of the pointers followed by
245 * the strings. This has the advantage of being easy to allocate/free and being
246 * compatible with both unix and windows
249 /* Calculate the required size */
250 num
= Jim_ListLength(interp
, objPtr
);
254 size
= Jim_Length(objPtr
);
255 /* We need one \0 and one equal sign for each element.
256 * A list has at least one space for each element except the first.
257 * We only need one extra char for the extra null terminator.
261 envptr
= Jim_Alloc(sizeof(*envptr
) * (num
/ 2 + 1) + size
);
262 envdata
= (char *)&envptr
[num
/ 2 + 1];
265 for (i
= 0; i
< num
; i
+= 2) {
269 Jim_ListIndex(interp
, objPtr
, i
, &elemObj
, JIM_NONE
);
270 s1
= Jim_String(elemObj
);
271 Jim_ListIndex(interp
, objPtr
, i
+ 1, &elemObj
, JIM_NONE
);
272 s2
= Jim_String(elemObj
);
275 envdata
+= sprintf(envdata
, "%s=%s", s1
, s2
);
284 return Jim_GetEnviron();
289 * Frees the environment allocated by JimBuildEnv()
291 * Must pass original_environ.
293 static void JimFreeEnv(char **env
, char **original_environ
)
295 #ifdef jim_ext_tclcompat
296 if (env
!= original_environ
) {
303 * Create error messages for unusual process exits. An
304 * extra newline gets appended to each error message, but
305 * it gets removed below (in the same fashion that an
306 * extra newline in the command's output is removed).
308 static int JimCheckWaitStatus(Jim_Interp
*interp
, pidtype pid
, int waitStatus
)
310 Jim_Obj
*errorCode
= Jim_NewListObj(interp
, NULL
, 0);
313 if (WIFEXITED(waitStatus
)) {
314 if (WEXITSTATUS(waitStatus
) == 0) {
315 Jim_ListAppendElement(interp
, errorCode
, Jim_NewStringObj(interp
, "NONE", -1));
319 Jim_ListAppendElement(interp
, errorCode
, Jim_NewStringObj(interp
, "CHILDSTATUS", -1));
320 Jim_ListAppendElement(interp
, errorCode
, Jim_NewIntObj(interp
, (long)pid
));
321 Jim_ListAppendElement(interp
, errorCode
, Jim_NewIntObj(interp
, WEXITSTATUS(waitStatus
)));
328 if (WIFSIGNALED(waitStatus
)) {
329 type
= "CHILDKILLED";
334 action
= "suspended";
337 Jim_ListAppendElement(interp
, errorCode
, Jim_NewStringObj(interp
, type
, -1));
339 #ifdef jim_ext_signal
340 Jim_SetResultFormatted(interp
, "child %s by signal %s", action
, Jim_SignalId(WTERMSIG(waitStatus
)));
341 Jim_ListAppendElement(interp
, errorCode
, Jim_NewStringObj(interp
, Jim_SignalId(WTERMSIG(waitStatus
)), -1));
342 Jim_ListAppendElement(interp
, errorCode
, Jim_NewIntObj(interp
, pid
));
343 Jim_ListAppendElement(interp
, errorCode
, Jim_NewStringObj(interp
, Jim_SignalName(WTERMSIG(waitStatus
)), -1));
345 Jim_SetResultFormatted(interp
, "child %s by signal %d", action
, WTERMSIG(waitStatus
));
346 Jim_ListAppendElement(interp
, errorCode
, Jim_NewIntObj(interp
, WTERMSIG(waitStatus
)));
347 Jim_ListAppendElement(interp
, errorCode
, Jim_NewIntObj(interp
, (long)pid
));
348 Jim_ListAppendElement(interp
, errorCode
, Jim_NewIntObj(interp
, WTERMSIG(waitStatus
)));
351 Jim_SetGlobalVariableStr(interp
, "errorCode", errorCode
);
356 * Data structures of the following type are used by JimFork and
357 * JimWaitPids to keep track of child processes.
362 pidtype pid
; /* Process id of child. */
363 int status
; /* Status returned when child exited or suspended. */
364 int flags
; /* Various flag bits; see below for definitions. */
367 struct WaitInfoTable
{
368 struct WaitInfo
*info
;
374 * Flag bits in WaitInfo structures:
376 * WI_DETACHED - Non-zero means no-one cares about the
377 * process anymore. Ignore it until it
378 * exits, then forget about it.
381 #define WI_DETACHED 2
383 #define WAIT_TABLE_GROW_BY 4
385 static void JimFreeWaitInfoTable(struct Jim_Interp
*interp
, void *privData
)
387 struct WaitInfoTable
*table
= privData
;
389 Jim_Free(table
->info
);
393 static struct WaitInfoTable
*JimAllocWaitInfoTable(void)
395 struct WaitInfoTable
*table
= Jim_Alloc(sizeof(*table
));
397 table
->size
= table
->used
= 0;
403 * The main [exec] command
405 static int Jim_ExecCmd(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
407 fdtype outputId
; /* File id for output pipe. -1
408 * means command overrode. */
409 fdtype errorId
; /* File id for temporary file
410 * containing error output. */
415 * See if the command is to be run in background; if so, create
416 * the command, detach it, and return.
418 if (argc
> 1 && Jim_CompareStringImmediate(interp
, argv
[argc
- 1], "&")) {
423 numPids
= JimCreatePipeline(interp
, argc
- 1, argv
+ 1, &pidPtr
, NULL
, NULL
, NULL
);
427 /* The return value is a list of the pids */
428 listObj
= Jim_NewListObj(interp
, NULL
, 0);
429 for (i
= 0; i
< numPids
; i
++) {
430 Jim_ListAppendElement(interp
, listObj
, Jim_NewIntObj(interp
, (long)pidPtr
[i
]));
432 Jim_SetResult(interp
, listObj
);
433 JimDetachPids(interp
, numPids
, pidPtr
);
439 * Create the command's pipeline.
442 JimCreatePipeline(interp
, argc
- 1, argv
+ 1, &pidPtr
, NULL
, &outputId
, &errorId
);
449 * Read the child's output (if any) and put it into the result.
451 Jim_SetResultString(interp
, "", 0);
454 if (outputId
!= JIM_BAD_FD
) {
455 result
= JimAppendStreamToString(interp
, outputId
, Jim_GetResult(interp
));
457 Jim_SetResultErrno(interp
, "error reading from output pipe");
461 if (JimCleanupChildren(interp
, numPids
, pidPtr
, errorId
) != JIM_OK
) {
467 static void JimReapDetachedPids(struct WaitInfoTable
*table
)
469 struct WaitInfo
*waitPtr
;
476 for (waitPtr
= table
->info
, count
= table
->used
; count
> 0; waitPtr
++, count
--) {
477 if (waitPtr
->flags
& WI_DETACHED
) {
479 pidtype pid
= JimWaitPid(waitPtr
->pid
, &status
, WNOHANG
);
480 if (pid
!= JIM_BAD_PID
) {
481 if (waitPtr
!= &table
->info
[table
->used
- 1]) {
482 *waitPtr
= table
->info
[table
->used
- 1];
491 * Does waitpid() on the given pid, and then removes the
492 * entry from the wait table.
494 * Returns the pid if OK and updates *statusPtr with the status,
495 * or JIM_BAD_PID if the pid was not in the table.
497 static pidtype
JimWaitForProcess(struct WaitInfoTable
*table
, pidtype pid
, int *statusPtr
)
501 /* Find it in the table */
502 for (i
= 0; i
< table
->used
; i
++) {
503 if (pid
== table
->info
[i
].pid
) {
505 JimWaitPid(pid
, statusPtr
, 0);
507 /* Remove it from the table */
508 if (i
!= table
->used
- 1) {
509 table
->info
[i
] = table
->info
[table
->used
- 1];
521 *----------------------------------------------------------------------
525 * This procedure is called to indicate that one or more child
526 * processes have been placed in background and are no longer
527 * cared about. These children can be cleaned up with JimReapDetachedPids().
535 *----------------------------------------------------------------------
538 static void JimDetachPids(Jim_Interp
*interp
, int numPids
, const pidtype
*pidPtr
)
541 struct WaitInfoTable
*table
= Jim_CmdPrivData(interp
);
543 for (j
= 0; j
< numPids
; j
++) {
544 /* Find it in the table */
546 for (i
= 0; i
< table
->used
; i
++) {
547 if (pidPtr
[j
] == table
->info
[i
].pid
) {
548 table
->info
[i
].flags
|= WI_DETACHED
;
555 static FILE *JimGetAioFilehandle(Jim_Interp
*interp
, const char *name
)
560 fhObj
= Jim_NewStringObj(interp
, name
, -1);
561 Jim_IncrRefCount(fhObj
);
562 fh
= Jim_AioFilehandle(interp
, fhObj
);
563 Jim_DecrRefCount(interp
, fhObj
);
569 *----------------------------------------------------------------------
571 * JimCreatePipeline --
573 * Given an argc/argv array, instantiate a pipeline of processes
574 * as described by the argv.
577 * The return value is a count of the number of new processes
578 * created, or -1 if an error occurred while creating the pipeline.
579 * *pidArrayPtr is filled in with the address of a dynamically
580 * allocated array giving the ids of all of the processes. It
581 * is up to the caller to free this array when it isn't needed
582 * anymore. If inPipePtr is non-NULL, *inPipePtr is filled in
583 * with the file id for the input pipe for the pipeline (if any):
584 * the caller must eventually close this file. If outPipePtr
585 * isn't NULL, then *outPipePtr is filled in with the file id
586 * for the output pipe from the pipeline: the caller must close
587 * this file. If errFilePtr isn't NULL, then *errFilePtr is filled
588 * with a file id that may be used to read error output after the
589 * pipeline completes.
592 * Processes and pipes are created.
594 *----------------------------------------------------------------------
597 JimCreatePipeline(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, pidtype
**pidArrayPtr
,
598 fdtype
*inPipePtr
, fdtype
*outPipePtr
, fdtype
*errFilePtr
)
600 pidtype
*pidPtr
= NULL
; /* Points to malloc-ed array holding all
601 * the pids of child processes. */
602 int numPids
= 0; /* Actual number of processes that exist
603 * at *pidPtr right now. */
604 int cmdCount
; /* Count of number of distinct commands
605 * found in argc/argv. */
606 const char *input
= NULL
; /* Describes input for pipeline, depending
607 * on "inputFile". NULL means take input
608 * from stdin/pipe. */
610 #define FILE_NAME 0 /* input/output: filename */
611 #define FILE_APPEND 1 /* output only: filename, append */
612 #define FILE_HANDLE 2 /* input/output: filehandle */
613 #define FILE_TEXT 3 /* input only: input is actual text */
615 int inputFile
= FILE_NAME
; /* 1 means input is name of input file.
616 * 2 means input is filehandle name.
617 * 0 means input holds actual
618 * text to be input to command. */
620 int outputFile
= FILE_NAME
; /* 0 means output is the name of output file.
621 * 1 means output is the name of output file, and append.
622 * 2 means output is filehandle name.
623 * All this is ignored if output is NULL
625 int errorFile
= FILE_NAME
; /* 0 means error is the name of error file.
626 * 1 means error is the name of error file, and append.
627 * 2 means error is filehandle name.
628 * All this is ignored if error is NULL
630 const char *output
= NULL
; /* Holds name of output file to pipe to,
631 * or NULL if output goes to stdout/pipe. */
632 const char *error
= NULL
; /* Holds name of stderr file to pipe to,
633 * or NULL if stderr goes to stderr/pipe. */
634 fdtype inputId
= JIM_BAD_FD
;
635 /* Readable file id input to current command in
636 * pipeline (could be file or pipe). JIM_BAD_FD
637 * means use stdin. */
638 fdtype outputId
= JIM_BAD_FD
;
639 /* Writable file id for output from current
640 * command in pipeline (could be file or pipe).
641 * JIM_BAD_FD means use stdout. */
642 fdtype errorId
= JIM_BAD_FD
;
643 /* Writable file id for all standard error
644 * output from all commands in pipeline. JIM_BAD_FD
645 * means use stderr. */
646 fdtype lastOutputId
= JIM_BAD_FD
;
647 /* Write file id for output from last command
648 * in pipeline (could be file or pipe).
649 * -1 means use stdout. */
650 fdtype pipeIds
[2]; /* File ids for pipe that's being created. */
651 int firstArg
, lastArg
; /* Indexes of first and last arguments in
652 * current command. */
657 struct WaitInfoTable
*table
= Jim_CmdPrivData(interp
);
659 /* Holds the args which will be used to exec */
660 char **arg_array
= Jim_Alloc(sizeof(*arg_array
) * (argc
+ 1));
663 JimReapDetachedPids(table
);
665 if (inPipePtr
!= NULL
) {
666 *inPipePtr
= JIM_BAD_FD
;
668 if (outPipePtr
!= NULL
) {
669 *outPipePtr
= JIM_BAD_FD
;
671 if (errFilePtr
!= NULL
) {
672 *errFilePtr
= JIM_BAD_FD
;
674 pipeIds
[0] = pipeIds
[1] = JIM_BAD_FD
;
677 * First, scan through all the arguments to figure out the structure
678 * of the pipeline. Count the number of distinct processes (it's the
679 * number of "|" arguments). If there are "<", "<<", or ">" arguments
680 * then make note of input and output redirection and remove these
681 * arguments and the arguments that follow them.
685 for (i
= 0; i
< argc
; i
++) {
686 const char *arg
= Jim_String(argv
[i
]);
689 inputFile
= FILE_NAME
;
692 inputFile
= FILE_TEXT
;
695 else if (*input
== '@') {
696 inputFile
= FILE_HANDLE
;
700 if (!*input
&& ++i
< argc
) {
701 input
= Jim_String(argv
[i
]);
704 else if (arg
[0] == '>') {
707 outputFile
= FILE_NAME
;
710 if (*output
== '>') {
711 outputFile
= FILE_APPEND
;
714 if (*output
== '&') {
715 /* Redirect stderr too */
719 if (*output
== '@') {
720 outputFile
= FILE_HANDLE
;
723 if (!*output
&& ++i
< argc
) {
724 output
= Jim_String(argv
[i
]);
727 errorFile
= outputFile
;
731 else if (arg
[0] == '2' && arg
[1] == '>') {
733 errorFile
= FILE_NAME
;
736 errorFile
= FILE_HANDLE
;
739 else if (*error
== '>') {
740 errorFile
= FILE_APPEND
;
743 if (!*error
&& ++i
< argc
) {
744 error
= Jim_String(argv
[i
]);
748 if (strcmp(arg
, "|") == 0 || strcmp(arg
, "|&") == 0) {
749 if (i
== lastBar
+ 1 || i
== argc
- 1) {
750 Jim_SetResultString(interp
, "illegal use of | or |& in command", -1);
756 /* Either |, |& or a "normal" arg, so store it in the arg array */
757 arg_array
[arg_count
++] = (char *)arg
;
762 Jim_SetResultFormatted(interp
, "can't specify \"%s\" as last word in command", arg
);
767 if (arg_count
== 0) {
768 Jim_SetResultString(interp
, "didn't specify command to execute", -1);
774 /* Must do this before vfork(), so do it now */
775 save_environ
= JimSaveEnv(JimBuildEnv(interp
));
778 * Set up the redirected input source for the pipeline, if
782 if (inputFile
== FILE_TEXT
) {
784 * Immediate data in command. Create temporary file and
785 * put data into file.
787 inputId
= JimCreateTemp(interp
, input
);
788 if (inputId
== JIM_BAD_FD
) {
792 else if (inputFile
== FILE_HANDLE
) {
793 /* Should be a file descriptor */
794 FILE *fh
= JimGetAioFilehandle(interp
, input
);
799 inputId
= JimDupFd(JimFileno(fh
));
803 * File redirection. Just open the file.
805 inputId
= JimOpenForRead(input
);
806 if (inputId
== JIM_BAD_FD
) {
807 Jim_SetResultFormatted(interp
, "couldn't read file \"%s\": %s", input
, JimStrError());
812 else if (inPipePtr
!= NULL
) {
813 if (JimPipe(pipeIds
) != 0) {
814 Jim_SetResultErrno(interp
, "couldn't create input pipe for command");
817 inputId
= pipeIds
[0];
818 *inPipePtr
= pipeIds
[1];
819 pipeIds
[0] = pipeIds
[1] = JIM_BAD_FD
;
823 * Set up the redirected output sink for the pipeline from one
824 * of two places, if requested.
826 if (output
!= NULL
) {
827 if (outputFile
== FILE_HANDLE
) {
828 FILE *fh
= JimGetAioFilehandle(interp
, output
);
833 lastOutputId
= JimDupFd(JimFileno(fh
));
837 * Output is to go to a file.
839 lastOutputId
= JimOpenForWrite(output
, outputFile
== FILE_APPEND
);
840 if (lastOutputId
== JIM_BAD_FD
) {
841 Jim_SetResultFormatted(interp
, "couldn't write file \"%s\": %s", output
, JimStrError());
846 else if (outPipePtr
!= NULL
) {
848 * Output is to go to a pipe.
850 if (JimPipe(pipeIds
) != 0) {
851 Jim_SetResultErrno(interp
, "couldn't create output pipe");
854 lastOutputId
= pipeIds
[1];
855 *outPipePtr
= pipeIds
[0];
856 pipeIds
[0] = pipeIds
[1] = JIM_BAD_FD
;
858 /* If we are redirecting stderr with 2>filename or 2>@fileId, then we ignore errFilePtr */
860 if (errorFile
== FILE_HANDLE
) {
861 if (strcmp(error
, "1") == 0) {
863 if (lastOutputId
!= JIM_BAD_FD
) {
864 errorId
= JimDupFd(lastOutputId
);
867 /* No redirection of stdout, so just use 2>@stdout */
871 if (errorId
== JIM_BAD_FD
) {
872 FILE *fh
= JimGetAioFilehandle(interp
, error
);
877 errorId
= JimDupFd(JimFileno(fh
));
882 * Output is to go to a file.
884 errorId
= JimOpenForWrite(error
, errorFile
== FILE_APPEND
);
885 if (errorId
== JIM_BAD_FD
) {
886 Jim_SetResultFormatted(interp
, "couldn't write file \"%s\": %s", error
, JimStrError());
891 else if (errFilePtr
!= NULL
) {
893 * Set up the standard error output sink for the pipeline, if
894 * requested. Use a temporary file which is opened, then deleted.
895 * Could potentially just use pipe, but if it filled up it could
896 * cause the pipeline to deadlock: we'd be waiting for processes
897 * to complete before reading stderr, and processes couldn't complete
898 * because stderr was backed up.
900 errorId
= JimCreateTemp(interp
, NULL
);
901 if (errorId
== JIM_BAD_FD
) {
904 *errFilePtr
= JimDupFd(errorId
);
908 * Scan through the argc array, forking off a process for each
909 * group of arguments between "|" arguments.
912 pidPtr
= Jim_Alloc(cmdCount
* sizeof(*pidPtr
));
913 for (i
= 0; i
< numPids
; i
++) {
914 pidPtr
[i
] = JIM_BAD_PID
;
916 for (firstArg
= 0; firstArg
< arg_count
; numPids
++, firstArg
= lastArg
+ 1) {
917 int pipe_dup_err
= 0;
918 fdtype origErrorId
= errorId
;
920 for (lastArg
= firstArg
; lastArg
< arg_count
; lastArg
++) {
921 if (arg_array
[lastArg
][0] == '|') {
922 if (arg_array
[lastArg
][1] == '&') {
928 /* Replace | with NULL for execv() */
929 arg_array
[lastArg
] = NULL
;
930 if (lastArg
== arg_count
) {
931 outputId
= lastOutputId
;
934 if (JimPipe(pipeIds
) != 0) {
935 Jim_SetResultErrno(interp
, "couldn't create pipe");
938 outputId
= pipeIds
[1];
941 /* Now fork the child */
944 pid
= JimStartWinProcess(interp
, &arg_array
[firstArg
], save_environ
? save_environ
[0] : NULL
, inputId
, outputId
, errorId
);
945 if (pid
== JIM_BAD_PID
) {
946 Jim_SetResultFormatted(interp
, "couldn't exec \"%s\"", arg_array
[firstArg
]);
951 * Disable SIGPIPE signals: if they were allowed, this process
952 * might go away unexpectedly if children misbehave. This code
953 * can potentially interfere with other application code that
954 * expects to handle SIGPIPEs; what's really needed is an
955 * arbiter for signals to allow them to be "shared".
957 if (table
->info
== NULL
) {
958 (void)signal(SIGPIPE
, SIG_IGN
);
961 /* Need to do this befor vfork() */
967 * Make a new process and enter it into the table if the fork
972 Jim_SetResultErrno(interp
, "couldn't fork child process");
978 if (inputId
!= -1) dup2(inputId
, 0);
979 if (outputId
!= -1) dup2(outputId
, 1);
980 if (errorId
!= -1) dup2(errorId
, 2);
982 for (i
= 3; (i
<= outputId
) || (i
<= inputId
) || (i
<= errorId
); i
++) {
986 execvp(arg_array
[firstArg
], &arg_array
[firstArg
]);
988 /* Need to prep an error message before vfork(), just in case */
989 fprintf(stderr
, "couldn't exec \"%s\"", arg_array
[firstArg
]);
997 * Enlarge the wait table if there isn't enough space for a new
1000 if (table
->used
== table
->size
) {
1001 table
->size
+= WAIT_TABLE_GROW_BY
;
1002 table
->info
= Jim_Realloc(table
->info
, table
->size
* sizeof(*table
->info
));
1005 table
->info
[table
->used
].pid
= pid
;
1006 table
->info
[table
->used
].flags
= 0;
1009 pidPtr
[numPids
] = pid
;
1011 /* Restore in case of pipe_dup_err */
1012 errorId
= origErrorId
;
1015 * Close off our copies of file descriptors that were set up for
1016 * this child, then set up the input for the next child.
1019 if (inputId
!= JIM_BAD_FD
) {
1020 JimCloseFd(inputId
);
1022 if (outputId
!= JIM_BAD_FD
) {
1023 JimCloseFd(outputId
);
1025 inputId
= pipeIds
[0];
1026 pipeIds
[0] = pipeIds
[1] = JIM_BAD_FD
;
1028 *pidArrayPtr
= pidPtr
;
1031 * All done. Cleanup open files lying around and then return.
1035 if (inputId
!= JIM_BAD_FD
) {
1036 JimCloseFd(inputId
);
1038 if (lastOutputId
!= JIM_BAD_FD
) {
1039 JimCloseFd(lastOutputId
);
1041 if (errorId
!= JIM_BAD_FD
) {
1042 JimCloseFd(errorId
);
1044 Jim_Free(arg_array
);
1046 JimRestoreEnv(save_environ
);
1051 * An error occurred. There could have been extra files open, such
1052 * as pipes between children. Clean them all up. Detach any child
1053 * processes that have been created.
1057 if ((inPipePtr
!= NULL
) && (*inPipePtr
!= JIM_BAD_FD
)) {
1058 JimCloseFd(*inPipePtr
);
1059 *inPipePtr
= JIM_BAD_FD
;
1061 if ((outPipePtr
!= NULL
) && (*outPipePtr
!= JIM_BAD_FD
)) {
1062 JimCloseFd(*outPipePtr
);
1063 *outPipePtr
= JIM_BAD_FD
;
1065 if ((errFilePtr
!= NULL
) && (*errFilePtr
!= JIM_BAD_FD
)) {
1066 JimCloseFd(*errFilePtr
);
1067 *errFilePtr
= JIM_BAD_FD
;
1069 if (pipeIds
[0] != JIM_BAD_FD
) {
1070 JimCloseFd(pipeIds
[0]);
1072 if (pipeIds
[1] != JIM_BAD_FD
) {
1073 JimCloseFd(pipeIds
[1]);
1075 if (pidPtr
!= NULL
) {
1076 for (i
= 0; i
< numPids
; i
++) {
1077 if (pidPtr
[i
] != JIM_BAD_PID
) {
1078 JimDetachPids(interp
, 1, &pidPtr
[i
]);
1088 *----------------------------------------------------------------------
1090 * JimCleanupChildren --
1092 * This is a utility procedure used to wait for child processes
1093 * to exit, record information about abnormal exits, and then
1094 * collect any stderr output generated by them.
1097 * The return value is a standard Tcl result. If anything at
1098 * weird happened with the child processes, JIM_ERROR is returned
1099 * and a message is left in interp->result.
1102 * If the last character of interp->result is a newline, then it
1103 * is removed. File errorId gets closed, and pidPtr is freed
1104 * back to the storage allocator.
1106 *----------------------------------------------------------------------
1109 static int JimCleanupChildren(Jim_Interp
*interp
, int numPids
, pidtype
*pidPtr
, fdtype errorId
)
1111 struct WaitInfoTable
*table
= Jim_CmdPrivData(interp
);
1112 int result
= JIM_OK
;
1115 for (i
= 0; i
< numPids
; i
++) {
1117 if (JimWaitForProcess(table
, pidPtr
[i
], &waitStatus
) != JIM_BAD_PID
) {
1118 if (JimCheckWaitStatus(interp
, pidPtr
[i
], waitStatus
) != JIM_OK
) {
1126 * Read the standard error file. If there's anything there,
1127 * then add the file's contents to the result
1130 if (errorId
!= JIM_BAD_FD
) {
1131 JimRewindFd(errorId
);
1132 if (JimAppendStreamToString(interp
, errorId
, Jim_GetResult(interp
)) != JIM_OK
) {
1137 JimTrimTrailingNewline(interp
);
1142 int Jim_execInit(Jim_Interp
*interp
)
1144 if (Jim_PackageProvide(interp
, "exec", "1.0", JIM_ERRMSG
))
1146 Jim_CreateCommand(interp
, "exec", Jim_ExecCmd
, JimAllocWaitInfoTable(), JimFreeWaitInfoTable
);
1150 #if defined(__MINGW32__)
1151 /* Windows-specific (mingw) implementation */
1153 static SECURITY_ATTRIBUTES
*JimStdSecAttrs(void)
1155 static SECURITY_ATTRIBUTES secAtts
;
1157 secAtts
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
1158 secAtts
.lpSecurityDescriptor
= NULL
;
1159 secAtts
.bInheritHandle
= TRUE
;
1163 static int JimErrno(void)
1165 switch (GetLastError()) {
1166 case ERROR_FILE_NOT_FOUND
: return ENOENT
;
1167 case ERROR_PATH_NOT_FOUND
: return ENOENT
;
1168 case ERROR_TOO_MANY_OPEN_FILES
: return EMFILE
;
1169 case ERROR_ACCESS_DENIED
: return EACCES
;
1170 case ERROR_INVALID_HANDLE
: return EBADF
;
1171 case ERROR_BAD_ENVIRONMENT
: return E2BIG
;
1172 case ERROR_BAD_FORMAT
: return ENOEXEC
;
1173 case ERROR_INVALID_ACCESS
: return EACCES
;
1174 case ERROR_INVALID_DRIVE
: return ENOENT
;
1175 case ERROR_CURRENT_DIRECTORY
: return EACCES
;
1176 case ERROR_NOT_SAME_DEVICE
: return EXDEV
;
1177 case ERROR_NO_MORE_FILES
: return ENOENT
;
1178 case ERROR_WRITE_PROTECT
: return EROFS
;
1179 case ERROR_BAD_UNIT
: return ENXIO
;
1180 case ERROR_NOT_READY
: return EBUSY
;
1181 case ERROR_BAD_COMMAND
: return EIO
;
1182 case ERROR_CRC
: return EIO
;
1183 case ERROR_BAD_LENGTH
: return EIO
;
1184 case ERROR_SEEK
: return EIO
;
1185 case ERROR_WRITE_FAULT
: return EIO
;
1186 case ERROR_READ_FAULT
: return EIO
;
1187 case ERROR_GEN_FAILURE
: return EIO
;
1188 case ERROR_SHARING_VIOLATION
: return EACCES
;
1189 case ERROR_LOCK_VIOLATION
: return EACCES
;
1190 case ERROR_SHARING_BUFFER_EXCEEDED
: return ENFILE
;
1191 case ERROR_HANDLE_DISK_FULL
: return ENOSPC
;
1192 case ERROR_NOT_SUPPORTED
: return ENODEV
;
1193 case ERROR_REM_NOT_LIST
: return EBUSY
;
1194 case ERROR_DUP_NAME
: return EEXIST
;
1195 case ERROR_BAD_NETPATH
: return ENOENT
;
1196 case ERROR_NETWORK_BUSY
: return EBUSY
;
1197 case ERROR_DEV_NOT_EXIST
: return ENODEV
;
1198 case ERROR_TOO_MANY_CMDS
: return EAGAIN
;
1199 case ERROR_ADAP_HDW_ERR
: return EIO
;
1200 case ERROR_BAD_NET_RESP
: return EIO
;
1201 case ERROR_UNEXP_NET_ERR
: return EIO
;
1202 case ERROR_NETNAME_DELETED
: return ENOENT
;
1203 case ERROR_NETWORK_ACCESS_DENIED
: return EACCES
;
1204 case ERROR_BAD_DEV_TYPE
: return ENODEV
;
1205 case ERROR_BAD_NET_NAME
: return ENOENT
;
1206 case ERROR_TOO_MANY_NAMES
: return ENFILE
;
1207 case ERROR_TOO_MANY_SESS
: return EIO
;
1208 case ERROR_SHARING_PAUSED
: return EAGAIN
;
1209 case ERROR_REDIR_PAUSED
: return EAGAIN
;
1210 case ERROR_FILE_EXISTS
: return EEXIST
;
1211 case ERROR_CANNOT_MAKE
: return ENOSPC
;
1212 case ERROR_OUT_OF_STRUCTURES
: return ENFILE
;
1213 case ERROR_ALREADY_ASSIGNED
: return EEXIST
;
1214 case ERROR_INVALID_PASSWORD
: return EPERM
;
1215 case ERROR_NET_WRITE_FAULT
: return EIO
;
1216 case ERROR_NO_PROC_SLOTS
: return EAGAIN
;
1217 case ERROR_DISK_CHANGE
: return EXDEV
;
1218 case ERROR_BROKEN_PIPE
: return EPIPE
;
1219 case ERROR_OPEN_FAILED
: return ENOENT
;
1220 case ERROR_DISK_FULL
: return ENOSPC
;
1221 case ERROR_NO_MORE_SEARCH_HANDLES
: return EMFILE
;
1222 case ERROR_INVALID_TARGET_HANDLE
: return EBADF
;
1223 case ERROR_INVALID_NAME
: return ENOENT
;
1224 case ERROR_PROC_NOT_FOUND
: return ESRCH
;
1225 case ERROR_WAIT_NO_CHILDREN
: return ECHILD
;
1226 case ERROR_CHILD_NOT_COMPLETE
: return ECHILD
;
1227 case ERROR_DIRECT_ACCESS_HANDLE
: return EBADF
;
1228 case ERROR_SEEK_ON_DEVICE
: return ESPIPE
;
1229 case ERROR_BUSY_DRIVE
: return EAGAIN
;
1230 case ERROR_DIR_NOT_EMPTY
: return EEXIST
;
1231 case ERROR_NOT_LOCKED
: return EACCES
;
1232 case ERROR_BAD_PATHNAME
: return ENOENT
;
1233 case ERROR_LOCK_FAILED
: return EACCES
;
1234 case ERROR_ALREADY_EXISTS
: return EEXIST
;
1235 case ERROR_FILENAME_EXCED_RANGE
: return ENAMETOOLONG
;
1236 case ERROR_BAD_PIPE
: return EPIPE
;
1237 case ERROR_PIPE_BUSY
: return EAGAIN
;
1238 case ERROR_PIPE_NOT_CONNECTED
: return EPIPE
;
1239 case ERROR_DIRECTORY
: return ENOTDIR
;
1244 static int JimPipe(fdtype pipefd
[2])
1246 if (CreatePipe(&pipefd
[0], &pipefd
[1], NULL
, 0)) {
1252 static fdtype
JimDupFd(fdtype infd
)
1255 pidtype pid
= GetCurrentProcess();
1257 if (DuplicateHandle(pid
, infd
, pid
, &dupfd
, 0, TRUE
, DUPLICATE_SAME_ACCESS
)) {
1263 static int JimRewindFd(fdtype fd
)
1265 return SetFilePointer(fd
, 0, NULL
, FILE_BEGIN
) == INVALID_SET_FILE_POINTER
? -1 : 0;
1269 static int JimReadFd(fdtype fd
, char *buffer
, size_t len
)
1273 if (ReadFile(fd
, buffer
, len
, &num
, NULL
)) {
1276 if (GetLastError() == ERROR_HANDLE_EOF
|| GetLastError() == ERROR_BROKEN_PIPE
) {
1283 static FILE *JimFdOpenForRead(fdtype fd
)
1285 return _fdopen(_open_osfhandle((int)fd
, _O_RDONLY
| _O_TEXT
), "r");
1288 static fdtype
JimFileno(FILE *fh
)
1290 return (fdtype
)_get_osfhandle(_fileno(fh
));
1293 static fdtype
JimOpenForRead(const char *filename
)
1295 return CreateFile(filename
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1296 JimStdSecAttrs(), OPEN_EXISTING
, 0, NULL
);
1299 static fdtype
JimOpenForWrite(const char *filename
, int append
)
1301 return CreateFile(filename
, append
? FILE_APPEND_DATA
: GENERIC_WRITE
, FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1302 JimStdSecAttrs(), append
? OPEN_ALWAYS
: CREATE_ALWAYS
, 0, (HANDLE
) NULL
);
1305 static FILE *JimFdOpenForWrite(fdtype fd
)
1307 return _fdopen(_open_osfhandle((int)fd
, _O_TEXT
), "w");
1310 static pidtype
JimWaitPid(pidtype pid
, int *status
, int nohang
)
1312 DWORD ret
= WaitForSingleObject(pid
, nohang
? 0 : INFINITE
);
1313 if (ret
== WAIT_TIMEOUT
|| ret
== WAIT_FAILED
) {
1314 /* WAIT_TIMEOUT can only happend with WNOHANG */
1317 GetExitCodeProcess(pid
, &ret
);
1323 static HANDLE
JimCreateTemp(Jim_Interp
*interp
, const char *contents
)
1325 char name
[MAX_PATH
];
1328 if (!GetTempPath(MAX_PATH
, name
) || !GetTempFileName(name
, "JIM", 0, name
)) {
1332 handle
= CreateFile(name
, GENERIC_READ
| GENERIC_WRITE
, 0, JimStdSecAttrs(),
1333 CREATE_ALWAYS
, FILE_ATTRIBUTE_TEMPORARY
| FILE_FLAG_DELETE_ON_CLOSE
,
1336 if (handle
== INVALID_HANDLE_VALUE
) {
1340 if (contents
!= NULL
) {
1341 /* Use fdopen() to get automatic text-mode translation */
1342 FILE *fh
= JimFdOpenForWrite(JimDupFd(handle
));
1347 if (fwrite(contents
, strlen(contents
), 1, fh
) != 1) {
1351 fseek(fh
, 0, SEEK_SET
);
1357 Jim_SetResultErrno(interp
, "failed to create temp file");
1358 CloseHandle(handle
);
1364 JimWinFindExecutable(const char *originalName
, char fullPath
[MAX_PATH
])
1367 static char extensions
[][5] = {".exe", "", ".bat"};
1369 for (i
= 0; i
< (int) (sizeof(extensions
) / sizeof(extensions
[0])); i
++) {
1370 lstrcpyn(fullPath
, originalName
, MAX_PATH
- 5);
1371 lstrcat(fullPath
, extensions
[i
]);
1373 if (SearchPath(NULL
, fullPath
, NULL
, MAX_PATH
, fullPath
, NULL
) == 0) {
1376 if (GetFileAttributes(fullPath
) & FILE_ATTRIBUTE_DIRECTORY
) {
1385 static char **JimSaveEnv(char **env
)
1390 static void JimRestoreEnv(char **env
)
1392 JimFreeEnv(env
, NULL
);
1396 JimWinBuildCommandLine(Jim_Interp
*interp
, char **argv
)
1398 char *start
, *special
;
1401 Jim_Obj
*strObj
= Jim_NewStringObj(interp
, "", 0);
1403 for (i
= 0; argv
[i
]; i
++) {
1405 Jim_AppendString(interp
, strObj
, " ", 1);
1408 if (argv
[i
][0] == '\0') {
1413 for (start
= argv
[i
]; *start
!= '\0'; start
++) {
1414 if (isspace(UCHAR(*start
))) {
1421 Jim_AppendString(interp
, strObj
, "\"" , 1);
1425 for (special
= argv
[i
]; ; ) {
1426 if ((*special
== '\\') && (special
[1] == '\\' ||
1427 special
[1] == '"' || (quote
&& special
[1] == '\0'))) {
1428 Jim_AppendString(interp
, strObj
, start
, special
- start
);
1432 if (*special
== '"' || (quote
&& *special
== '\0')) {
1434 * N backslashes followed a quote -> insert
1435 * N * 2 + 1 backslashes then a quote.
1438 Jim_AppendString(interp
, strObj
, start
, special
- start
);
1441 if (*special
!= '\\') {
1445 Jim_AppendString(interp
, strObj
, start
, special
- start
);
1448 if (*special
== '"') {
1449 if (special
== start
) {
1450 Jim_AppendString(interp
, strObj
, "\"", 1);
1453 Jim_AppendString(interp
, strObj
, start
, special
- start
);
1455 Jim_AppendString(interp
, strObj
, "\\\"", 2);
1456 start
= special
+ 1;
1458 if (*special
== '\0') {
1463 Jim_AppendString(interp
, strObj
, start
, special
- start
);
1465 Jim_AppendString(interp
, strObj
, "\"", 1);
1472 JimStartWinProcess(Jim_Interp
*interp
, char **argv
, char *env
, fdtype inputId
, fdtype outputId
, fdtype errorId
)
1474 STARTUPINFO startInfo
;
1475 PROCESS_INFORMATION procInfo
;
1477 char execPath
[MAX_PATH
];
1479 pidtype pid
= JIM_BAD_PID
;
1480 Jim_Obj
*cmdLineObj
;
1482 if (JimWinFindExecutable(argv
[0], execPath
) < 0) {
1485 originalName
= argv
[0];
1488 hProcess
= GetCurrentProcess();
1489 cmdLineObj
= JimWinBuildCommandLine(interp
, argv
);
1492 * STARTF_USESTDHANDLES must be used to pass handles to child process.
1493 * Using SetStdHandle() and/or dup2() only works when a console mode
1494 * parent process is spawning an attached console mode child process.
1497 ZeroMemory(&startInfo
, sizeof(startInfo
));
1498 startInfo
.cb
= sizeof(startInfo
);
1499 startInfo
.dwFlags
= STARTF_USESTDHANDLES
;
1500 startInfo
.hStdInput
= INVALID_HANDLE_VALUE
;
1501 startInfo
.hStdOutput
= INVALID_HANDLE_VALUE
;
1502 startInfo
.hStdError
= INVALID_HANDLE_VALUE
;
1505 * Duplicate all the handles which will be passed off as stdin, stdout
1506 * and stderr of the child process. The duplicate handles are set to
1507 * be inheritable, so the child process can use them.
1509 if (inputId
== JIM_BAD_FD
) {
1510 if (CreatePipe(&startInfo
.hStdInput
, &h
, JimStdSecAttrs(), 0) != FALSE
) {
1514 DuplicateHandle(hProcess
, inputId
, hProcess
, &startInfo
.hStdInput
,
1515 0, TRUE
, DUPLICATE_SAME_ACCESS
);
1517 if (startInfo
.hStdInput
== JIM_BAD_FD
) {
1521 if (outputId
== JIM_BAD_FD
) {
1522 startInfo
.hStdOutput
= CreateFile("NUL:", GENERIC_WRITE
, 0,
1523 JimStdSecAttrs(), OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
1525 DuplicateHandle(hProcess
, outputId
, hProcess
, &startInfo
.hStdOutput
,
1526 0, TRUE
, DUPLICATE_SAME_ACCESS
);
1528 if (startInfo
.hStdOutput
== JIM_BAD_FD
) {
1532 if (errorId
== JIM_BAD_FD
) {
1534 * If handle was not set, errors should be sent to an infinitely
1538 startInfo
.hStdError
= CreateFile("NUL:", GENERIC_WRITE
, 0,
1539 JimStdSecAttrs(), OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
1541 DuplicateHandle(hProcess
, errorId
, hProcess
, &startInfo
.hStdError
,
1542 0, TRUE
, DUPLICATE_SAME_ACCESS
);
1544 if (startInfo
.hStdError
== JIM_BAD_FD
) {
1548 if (!CreateProcess(NULL
, (char *)Jim_String(cmdLineObj
), NULL
, NULL
, TRUE
,
1549 0, env
, NULL
, &startInfo
, &procInfo
)) {
1554 * "When an application spawns a process repeatedly, a new thread
1555 * instance will be created for each process but the previous
1556 * instances may not be cleaned up. This results in a significant
1557 * virtual memory loss each time the process is spawned. If there
1558 * is a WaitForInputIdle() call between CreateProcess() and
1559 * CloseHandle(), the problem does not occur." PSS ID Number: Q124121
1562 WaitForInputIdle(procInfo
.hProcess
, 5000);
1563 CloseHandle(procInfo
.hThread
);
1565 pid
= procInfo
.hProcess
;
1568 Jim_FreeNewObj(interp
, cmdLineObj
);
1569 if (startInfo
.hStdInput
!= JIM_BAD_FD
) {
1570 CloseHandle(startInfo
.hStdInput
);
1572 if (startInfo
.hStdOutput
!= JIM_BAD_FD
) {
1573 CloseHandle(startInfo
.hStdOutput
);
1575 if (startInfo
.hStdError
!= JIM_BAD_FD
) {
1576 CloseHandle(startInfo
.hStdError
);
1581 /* Unix-specific implementation */
1582 static int JimOpenForWrite(const char *filename
, int append
)
1584 return open(filename
, O_WRONLY
| O_CREAT
| (append
? O_APPEND
: O_TRUNC
), 0666);
1587 static int JimRewindFd(int fd
)
1589 return lseek(fd
, 0L, SEEK_SET
);
1592 static int JimCreateTemp(Jim_Interp
*interp
, const char *contents
)
1594 char inName
[] = "/tmp/tcl.tmp.XXXXXX";
1596 int fd
= mkstemp(inName
);
1597 if (fd
== JIM_BAD_FD
) {
1598 Jim_SetResultErrno(interp
, "couldn't create temp file");
1603 int length
= strlen(contents
);
1604 if (write(fd
, contents
, length
) != length
) {
1605 Jim_SetResultErrno(interp
, "couldn't write temp file");
1609 lseek(fd
, 0L, SEEK_SET
);
1614 static char **JimSaveEnv(char **env
)
1616 char **saveenv
= Jim_GetEnviron();
1617 Jim_SetEnviron(env
);
1621 static void JimRestoreEnv(char **env
)
1623 JimFreeEnv(Jim_GetEnviron(), env
);
1624 Jim_SetEnviron(env
);