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 #define execvpe(ARG0, ARGV, ENV) execvp(ARG0, ARGV)
148 static const char *JimStrError(void);
149 static char **JimSaveEnv(char **env
);
150 static void JimRestoreEnv(char **env
);
151 static int JimCreatePipeline(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
,
152 pidtype
**pidArrayPtr
, fdtype
*inPipePtr
, fdtype
*outPipePtr
, fdtype
*errFilePtr
);
153 static void JimDetachPids(Jim_Interp
*interp
, int numPids
, const pidtype
*pidPtr
);
154 static int JimCleanupChildren(Jim_Interp
*interp
, int numPids
, pidtype
*pidPtr
, fdtype errorId
);
155 static fdtype
JimCreateTemp(Jim_Interp
*interp
, const char *contents
, int len
);
156 static fdtype
JimOpenForWrite(const char *filename
, int append
);
157 static int JimRewindFd(fdtype fd
);
159 static void Jim_SetResultErrno(Jim_Interp
*interp
, const char *msg
)
161 Jim_SetResultFormatted(interp
, "%s: %s", msg
, JimStrError());
164 static const char *JimStrError(void)
166 return strerror(JimErrno());
170 * If the last character of 'objPtr' is a newline, then remove
171 * the newline character.
173 static void Jim_RemoveTrailingNewline(Jim_Obj
*objPtr
)
176 const char *s
= Jim_GetString(objPtr
, &len
);
178 if (len
> 0 && s
[len
- 1] == '\n') {
180 objPtr
->bytes
[objPtr
->length
] = '\0';
185 * Read from 'fd', append the data to strObj and close 'fd'.
186 * Returns JIM_OK if OK, or JIM_ERR on error.
188 static int JimAppendStreamToString(Jim_Interp
*interp
, fdtype fd
, Jim_Obj
*strObj
)
191 FILE *fh
= JimFdOpenForRead(fd
);
197 int retval
= fread(buf
, 1, sizeof(buf
), fh
);
199 Jim_AppendString(interp
, strObj
, buf
, retval
);
201 if (retval
!= sizeof(buf
)) {
205 Jim_RemoveTrailingNewline(strObj
);
211 * Builds the environment array from $::env
213 * If $::env is not set, simply returns environ.
215 * Otherwise allocates the environ array from the contents of $::env
217 * If the exec fails, memory can be freed via JimFreeEnv()
219 static char **JimBuildEnv(Jim_Interp
*interp
)
228 Jim_Obj
*objPtr
= Jim_GetGlobalVariableStr(interp
, "env", JIM_NONE
);
231 return Jim_GetEnviron();
234 /* We build the array as a single block consisting of the pointers followed by
235 * the strings. This has the advantage of being easy to allocate/free and being
236 * compatible with both unix and windows
239 /* Calculate the required size */
240 num
= Jim_ListLength(interp
, objPtr
);
244 /* We need one \0 and one equal sign for each element.
245 * A list has at least one space for each element except the first.
246 * We need one extra char for the extra null terminator and one for the equal sign.
248 size
= Jim_Length(objPtr
) + 2;
250 envptr
= Jim_Alloc(sizeof(*envptr
) * (num
/ 2 + 1) + size
);
251 envdata
= (char *)&envptr
[num
/ 2 + 1];
254 for (i
= 0; i
< num
; i
+= 2) {
258 Jim_ListIndex(interp
, objPtr
, i
, &elemObj
, JIM_NONE
);
259 s1
= Jim_String(elemObj
);
260 Jim_ListIndex(interp
, objPtr
, i
+ 1, &elemObj
, JIM_NONE
);
261 s2
= Jim_String(elemObj
);
264 envdata
+= sprintf(envdata
, "%s=%s", s1
, s2
);
275 * Frees the environment allocated by JimBuildEnv()
277 * Must pass original_environ.
279 static void JimFreeEnv(char **env
, char **original_environ
)
281 if (env
!= original_environ
) {
287 * Create error messages for unusual process exits. An
288 * extra newline gets appended to each error message, but
289 * it gets removed below (in the same fashion that an
290 * extra newline in the command's output is removed).
292 static int JimCheckWaitStatus(Jim_Interp
*interp
, pidtype pid
, int waitStatus
)
294 Jim_Obj
*errorCode
= Jim_NewListObj(interp
, NULL
, 0);
297 if (WIFEXITED(waitStatus
)) {
298 if (WEXITSTATUS(waitStatus
) == 0) {
299 Jim_ListAppendElement(interp
, errorCode
, Jim_NewStringObj(interp
, "NONE", -1));
303 Jim_ListAppendElement(interp
, errorCode
, Jim_NewStringObj(interp
, "CHILDSTATUS", -1));
304 Jim_ListAppendElement(interp
, errorCode
, Jim_NewIntObj(interp
, (long)pid
));
305 Jim_ListAppendElement(interp
, errorCode
, Jim_NewIntObj(interp
, WEXITSTATUS(waitStatus
)));
312 if (WIFSIGNALED(waitStatus
)) {
313 type
= "CHILDKILLED";
318 action
= "suspended";
321 Jim_ListAppendElement(interp
, errorCode
, Jim_NewStringObj(interp
, type
, -1));
323 #ifdef jim_ext_signal
324 Jim_SetResultFormatted(interp
, "child %s by signal %s", action
, Jim_SignalId(WTERMSIG(waitStatus
)));
325 Jim_ListAppendElement(interp
, errorCode
, Jim_NewStringObj(interp
, Jim_SignalId(WTERMSIG(waitStatus
)), -1));
326 Jim_ListAppendElement(interp
, errorCode
, Jim_NewIntObj(interp
, pid
));
327 Jim_ListAppendElement(interp
, errorCode
, Jim_NewStringObj(interp
, Jim_SignalName(WTERMSIG(waitStatus
)), -1));
329 Jim_SetResultFormatted(interp
, "child %s by signal %d", action
, WTERMSIG(waitStatus
));
330 Jim_ListAppendElement(interp
, errorCode
, Jim_NewIntObj(interp
, WTERMSIG(waitStatus
)));
331 Jim_ListAppendElement(interp
, errorCode
, Jim_NewIntObj(interp
, (long)pid
));
332 Jim_ListAppendElement(interp
, errorCode
, Jim_NewIntObj(interp
, WTERMSIG(waitStatus
)));
335 Jim_SetGlobalVariableStr(interp
, "errorCode", errorCode
);
340 * Data structures of the following type are used by JimFork and
341 * JimWaitPids to keep track of child processes.
346 pidtype pid
; /* Process id of child. */
347 int status
; /* Status returned when child exited or suspended. */
348 int flags
; /* Various flag bits; see below for definitions. */
351 struct WaitInfoTable
{
352 struct WaitInfo
*info
;
358 * Flag bits in WaitInfo structures:
360 * WI_DETACHED - Non-zero means no-one cares about the
361 * process anymore. Ignore it until it
362 * exits, then forget about it.
365 #define WI_DETACHED 2
367 #define WAIT_TABLE_GROW_BY 4
369 static void JimFreeWaitInfoTable(struct Jim_Interp
*interp
, void *privData
)
371 struct WaitInfoTable
*table
= privData
;
373 Jim_Free(table
->info
);
377 static struct WaitInfoTable
*JimAllocWaitInfoTable(void)
379 struct WaitInfoTable
*table
= Jim_Alloc(sizeof(*table
));
381 table
->size
= table
->used
= 0;
387 * The main [exec] command
389 static int Jim_ExecCmd(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
391 fdtype outputId
; /* File id for output pipe. -1
392 * means command overrode. */
393 fdtype errorId
; /* File id for temporary file
394 * containing error output. */
399 * See if the command is to be run in background; if so, create
400 * the command, detach it, and return.
402 if (argc
> 1 && Jim_CompareStringImmediate(interp
, argv
[argc
- 1], "&")) {
407 numPids
= JimCreatePipeline(interp
, argc
- 1, argv
+ 1, &pidPtr
, NULL
, NULL
, NULL
);
411 /* The return value is a list of the pids */
412 listObj
= Jim_NewListObj(interp
, NULL
, 0);
413 for (i
= 0; i
< numPids
; i
++) {
414 Jim_ListAppendElement(interp
, listObj
, Jim_NewIntObj(interp
, (long)pidPtr
[i
]));
416 Jim_SetResult(interp
, listObj
);
417 JimDetachPids(interp
, numPids
, pidPtr
);
423 * Create the command's pipeline.
426 JimCreatePipeline(interp
, argc
- 1, argv
+ 1, &pidPtr
, NULL
, &outputId
, &errorId
);
433 * Read the child's output (if any) and put it into the result.
435 Jim_SetResultString(interp
, "", 0);
438 if (outputId
!= JIM_BAD_FD
) {
439 result
= JimAppendStreamToString(interp
, outputId
, Jim_GetResult(interp
));
441 Jim_SetResultErrno(interp
, "error reading from output pipe");
445 if (JimCleanupChildren(interp
, numPids
, pidPtr
, errorId
) != JIM_OK
) {
451 static void JimReapDetachedPids(struct WaitInfoTable
*table
)
453 struct WaitInfo
*waitPtr
;
461 waitPtr
= table
->info
;
463 for (count
= table
->used
; count
> 0; waitPtr
++, count
--) {
464 if (waitPtr
->flags
& WI_DETACHED
) {
466 pidtype pid
= JimWaitPid(waitPtr
->pid
, &status
, WNOHANG
);
467 if (pid
== waitPtr
->pid
) {
468 /* Process has exited, so remove it from the table */
473 if (waitPtr
!= &table
->info
[dest
]) {
474 table
->info
[dest
] = *waitPtr
;
481 * Does waitpid() on the given pid, and then removes the
482 * entry from the wait table.
484 * Returns the pid if OK and updates *statusPtr with the status,
485 * or JIM_BAD_PID if the pid was not in the table.
487 static pidtype
JimWaitForProcess(struct WaitInfoTable
*table
, pidtype pid
, int *statusPtr
)
491 /* Find it in the table */
492 for (i
= 0; i
< table
->used
; i
++) {
493 if (pid
== table
->info
[i
].pid
) {
495 JimWaitPid(pid
, statusPtr
, 0);
497 /* Remove it from the table */
498 if (i
!= table
->used
- 1) {
499 table
->info
[i
] = table
->info
[table
->used
- 1];
511 *----------------------------------------------------------------------
515 * This procedure is called to indicate that one or more child
516 * processes have been placed in background and are no longer
517 * cared about. These children can be cleaned up with JimReapDetachedPids().
525 *----------------------------------------------------------------------
528 static void JimDetachPids(Jim_Interp
*interp
, int numPids
, const pidtype
*pidPtr
)
531 struct WaitInfoTable
*table
= Jim_CmdPrivData(interp
);
533 for (j
= 0; j
< numPids
; j
++) {
534 /* Find it in the table */
536 for (i
= 0; i
< table
->used
; i
++) {
537 if (pidPtr
[j
] == table
->info
[i
].pid
) {
538 table
->info
[i
].flags
|= WI_DETACHED
;
545 static FILE *JimGetAioFilehandle(Jim_Interp
*interp
, const char *name
)
550 fhObj
= Jim_NewStringObj(interp
, name
, -1);
551 Jim_IncrRefCount(fhObj
);
552 fh
= Jim_AioFilehandle(interp
, fhObj
);
553 Jim_DecrRefCount(interp
, fhObj
);
559 *----------------------------------------------------------------------
561 * JimCreatePipeline --
563 * Given an argc/argv array, instantiate a pipeline of processes
564 * as described by the argv.
567 * The return value is a count of the number of new processes
568 * created, or -1 if an error occurred while creating the pipeline.
569 * *pidArrayPtr is filled in with the address of a dynamically
570 * allocated array giving the ids of all of the processes. It
571 * is up to the caller to free this array when it isn't needed
572 * anymore. If inPipePtr is non-NULL, *inPipePtr is filled in
573 * with the file id for the input pipe for the pipeline (if any):
574 * the caller must eventually close this file. If outPipePtr
575 * isn't NULL, then *outPipePtr is filled in with the file id
576 * for the output pipe from the pipeline: the caller must close
577 * this file. If errFilePtr isn't NULL, then *errFilePtr is filled
578 * with a file id that may be used to read error output after the
579 * pipeline completes.
582 * Processes and pipes are created.
584 *----------------------------------------------------------------------
587 JimCreatePipeline(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, pidtype
**pidArrayPtr
,
588 fdtype
*inPipePtr
, fdtype
*outPipePtr
, fdtype
*errFilePtr
)
590 pidtype
*pidPtr
= NULL
; /* Points to malloc-ed array holding all
591 * the pids of child processes. */
592 int numPids
= 0; /* Actual number of processes that exist
593 * at *pidPtr right now. */
594 int cmdCount
; /* Count of number of distinct commands
595 * found in argc/argv. */
596 const char *input
= NULL
; /* Describes input for pipeline, depending
597 * on "inputFile". NULL means take input
598 * from stdin/pipe. */
599 int input_len
= 0; /* Length of input, if relevant */
601 #define FILE_NAME 0 /* input/output: filename */
602 #define FILE_APPEND 1 /* output only: filename, append */
603 #define FILE_HANDLE 2 /* input/output: filehandle */
604 #define FILE_TEXT 3 /* input only: input is actual text */
606 int inputFile
= FILE_NAME
; /* 1 means input is name of input file.
607 * 2 means input is filehandle name.
608 * 0 means input holds actual
609 * text to be input to command. */
611 int outputFile
= FILE_NAME
; /* 0 means output is the name of output file.
612 * 1 means output is the name of output file, and append.
613 * 2 means output is filehandle name.
614 * All this is ignored if output is NULL
616 int errorFile
= FILE_NAME
; /* 0 means error is the name of error file.
617 * 1 means error is the name of error file, and append.
618 * 2 means error is filehandle name.
619 * All this is ignored if error is NULL
621 const char *output
= NULL
; /* Holds name of output file to pipe to,
622 * or NULL if output goes to stdout/pipe. */
623 const char *error
= NULL
; /* Holds name of stderr file to pipe to,
624 * or NULL if stderr goes to stderr/pipe. */
625 fdtype inputId
= JIM_BAD_FD
;
626 /* Readable file id input to current command in
627 * pipeline (could be file or pipe). JIM_BAD_FD
628 * means use stdin. */
629 fdtype outputId
= JIM_BAD_FD
;
630 /* Writable file id for output from current
631 * command in pipeline (could be file or pipe).
632 * JIM_BAD_FD means use stdout. */
633 fdtype errorId
= JIM_BAD_FD
;
634 /* Writable file id for all standard error
635 * output from all commands in pipeline. JIM_BAD_FD
636 * means use stderr. */
637 fdtype lastOutputId
= JIM_BAD_FD
;
638 /* Write file id for output from last command
639 * in pipeline (could be file or pipe).
640 * -1 means use stdout. */
641 fdtype pipeIds
[2]; /* File ids for pipe that's being created. */
642 int firstArg
, lastArg
; /* Indexes of first and last arguments in
643 * current command. */
648 struct WaitInfoTable
*table
= Jim_CmdPrivData(interp
);
650 /* Holds the args which will be used to exec */
651 char **arg_array
= Jim_Alloc(sizeof(*arg_array
) * (argc
+ 1));
654 JimReapDetachedPids(table
);
656 if (inPipePtr
!= NULL
) {
657 *inPipePtr
= JIM_BAD_FD
;
659 if (outPipePtr
!= NULL
) {
660 *outPipePtr
= JIM_BAD_FD
;
662 if (errFilePtr
!= NULL
) {
663 *errFilePtr
= JIM_BAD_FD
;
665 pipeIds
[0] = pipeIds
[1] = JIM_BAD_FD
;
668 * First, scan through all the arguments to figure out the structure
669 * of the pipeline. Count the number of distinct processes (it's the
670 * number of "|" arguments). If there are "<", "<<", or ">" arguments
671 * then make note of input and output redirection and remove these
672 * arguments and the arguments that follow them.
676 for (i
= 0; i
< argc
; i
++) {
677 const char *arg
= Jim_String(argv
[i
]);
680 inputFile
= FILE_NAME
;
683 inputFile
= FILE_TEXT
;
684 input_len
= Jim_Length(argv
[i
]) - 2;
687 else if (*input
== '@') {
688 inputFile
= FILE_HANDLE
;
692 if (!*input
&& ++i
< argc
) {
693 input
= Jim_GetString(argv
[i
], &input_len
);
696 else if (arg
[0] == '>') {
699 outputFile
= FILE_NAME
;
702 if (*output
== '>') {
703 outputFile
= FILE_APPEND
;
706 if (*output
== '&') {
707 /* Redirect stderr too */
711 if (*output
== '@') {
712 outputFile
= FILE_HANDLE
;
715 if (!*output
&& ++i
< argc
) {
716 output
= Jim_String(argv
[i
]);
719 errorFile
= outputFile
;
723 else if (arg
[0] == '2' && arg
[1] == '>') {
725 errorFile
= FILE_NAME
;
728 errorFile
= FILE_HANDLE
;
731 else if (*error
== '>') {
732 errorFile
= FILE_APPEND
;
735 if (!*error
&& ++i
< argc
) {
736 error
= Jim_String(argv
[i
]);
740 if (strcmp(arg
, "|") == 0 || strcmp(arg
, "|&") == 0) {
741 if (i
== lastBar
+ 1 || i
== argc
- 1) {
742 Jim_SetResultString(interp
, "illegal use of | or |& in command", -1);
748 /* Either |, |& or a "normal" arg, so store it in the arg array */
749 arg_array
[arg_count
++] = (char *)arg
;
754 Jim_SetResultFormatted(interp
, "can't specify \"%s\" as last word in command", arg
);
759 if (arg_count
== 0) {
760 Jim_SetResultString(interp
, "didn't specify command to execute", -1);
766 /* Must do this before vfork(), so do it now */
767 save_environ
= JimSaveEnv(JimBuildEnv(interp
));
770 * Set up the redirected input source for the pipeline, if
774 if (inputFile
== FILE_TEXT
) {
776 * Immediate data in command. Create temporary file and
777 * put data into file.
779 inputId
= JimCreateTemp(interp
, input
, input_len
);
780 if (inputId
== JIM_BAD_FD
) {
784 else if (inputFile
== FILE_HANDLE
) {
785 /* Should be a file descriptor */
786 FILE *fh
= JimGetAioFilehandle(interp
, input
);
791 inputId
= JimDupFd(JimFileno(fh
));
795 * File redirection. Just open the file.
797 inputId
= JimOpenForRead(input
);
798 if (inputId
== JIM_BAD_FD
) {
799 Jim_SetResultFormatted(interp
, "couldn't read file \"%s\": %s", input
, JimStrError());
804 else if (inPipePtr
!= NULL
) {
805 if (JimPipe(pipeIds
) != 0) {
806 Jim_SetResultErrno(interp
, "couldn't create input pipe for command");
809 inputId
= pipeIds
[0];
810 *inPipePtr
= pipeIds
[1];
811 pipeIds
[0] = pipeIds
[1] = JIM_BAD_FD
;
815 * Set up the redirected output sink for the pipeline from one
816 * of two places, if requested.
818 if (output
!= NULL
) {
819 if (outputFile
== FILE_HANDLE
) {
820 FILE *fh
= JimGetAioFilehandle(interp
, output
);
825 lastOutputId
= JimDupFd(JimFileno(fh
));
829 * Output is to go to a file.
831 lastOutputId
= JimOpenForWrite(output
, outputFile
== FILE_APPEND
);
832 if (lastOutputId
== JIM_BAD_FD
) {
833 Jim_SetResultFormatted(interp
, "couldn't write file \"%s\": %s", output
, JimStrError());
838 else if (outPipePtr
!= NULL
) {
840 * Output is to go to a pipe.
842 if (JimPipe(pipeIds
) != 0) {
843 Jim_SetResultErrno(interp
, "couldn't create output pipe");
846 lastOutputId
= pipeIds
[1];
847 *outPipePtr
= pipeIds
[0];
848 pipeIds
[0] = pipeIds
[1] = JIM_BAD_FD
;
850 /* If we are redirecting stderr with 2>filename or 2>@fileId, then we ignore errFilePtr */
852 if (errorFile
== FILE_HANDLE
) {
853 if (strcmp(error
, "1") == 0) {
855 if (lastOutputId
!= JIM_BAD_FD
) {
856 errorId
= JimDupFd(lastOutputId
);
859 /* No redirection of stdout, so just use 2>@stdout */
863 if (errorId
== JIM_BAD_FD
) {
864 FILE *fh
= JimGetAioFilehandle(interp
, error
);
869 errorId
= JimDupFd(JimFileno(fh
));
874 * Output is to go to a file.
876 errorId
= JimOpenForWrite(error
, errorFile
== FILE_APPEND
);
877 if (errorId
== JIM_BAD_FD
) {
878 Jim_SetResultFormatted(interp
, "couldn't write file \"%s\": %s", error
, JimStrError());
883 else if (errFilePtr
!= NULL
) {
885 * Set up the standard error output sink for the pipeline, if
886 * requested. Use a temporary file which is opened, then deleted.
887 * Could potentially just use pipe, but if it filled up it could
888 * cause the pipeline to deadlock: we'd be waiting for processes
889 * to complete before reading stderr, and processes couldn't complete
890 * because stderr was backed up.
892 errorId
= JimCreateTemp(interp
, NULL
, 0);
893 if (errorId
== JIM_BAD_FD
) {
896 *errFilePtr
= JimDupFd(errorId
);
900 * Scan through the argc array, forking off a process for each
901 * group of arguments between "|" arguments.
904 pidPtr
= Jim_Alloc(cmdCount
* sizeof(*pidPtr
));
905 for (i
= 0; i
< numPids
; i
++) {
906 pidPtr
[i
] = JIM_BAD_PID
;
908 for (firstArg
= 0; firstArg
< arg_count
; numPids
++, firstArg
= lastArg
+ 1) {
909 int pipe_dup_err
= 0;
910 fdtype origErrorId
= errorId
;
912 for (lastArg
= firstArg
; lastArg
< arg_count
; lastArg
++) {
913 if (arg_array
[lastArg
][0] == '|') {
914 if (arg_array
[lastArg
][1] == '&') {
920 /* Replace | with NULL for execv() */
921 arg_array
[lastArg
] = NULL
;
922 if (lastArg
== arg_count
) {
923 outputId
= lastOutputId
;
926 if (JimPipe(pipeIds
) != 0) {
927 Jim_SetResultErrno(interp
, "couldn't create pipe");
930 outputId
= pipeIds
[1];
933 /* Need to do this befor vfork() */
938 /* Now fork the child */
941 pid
= JimStartWinProcess(interp
, &arg_array
[firstArg
], save_environ
? save_environ
[0] : NULL
, inputId
, outputId
, errorId
);
942 if (pid
== JIM_BAD_PID
) {
943 Jim_SetResultFormatted(interp
, "couldn't exec \"%s\"", arg_array
[firstArg
]);
948 * Make a new process and enter it into the table if the fork
953 Jim_SetResultErrno(interp
, "couldn't fork child process");
959 if (inputId
!= -1) dup2(inputId
, 0);
960 if (outputId
!= -1) dup2(outputId
, 1);
961 if (errorId
!= -1) dup2(errorId
, 2);
963 for (i
= 3; (i
<= outputId
) || (i
<= inputId
) || (i
<= errorId
); i
++) {
967 /* Restore SIGPIPE behaviour */
968 (void)signal(SIGPIPE
, SIG_DFL
);
970 execvpe(arg_array
[firstArg
], &arg_array
[firstArg
], Jim_GetEnviron());
972 /* Need to prep an error message before vfork(), just in case */
973 fprintf(stderr
, "couldn't exec \"%s\"\n", arg_array
[firstArg
]);
981 * Enlarge the wait table if there isn't enough space for a new
984 if (table
->used
== table
->size
) {
985 table
->size
+= WAIT_TABLE_GROW_BY
;
986 table
->info
= Jim_Realloc(table
->info
, table
->size
* sizeof(*table
->info
));
989 table
->info
[table
->used
].pid
= pid
;
990 table
->info
[table
->used
].flags
= 0;
993 pidPtr
[numPids
] = pid
;
995 /* Restore in case of pipe_dup_err */
996 errorId
= origErrorId
;
999 * Close off our copies of file descriptors that were set up for
1000 * this child, then set up the input for the next child.
1003 if (inputId
!= JIM_BAD_FD
) {
1004 JimCloseFd(inputId
);
1006 if (outputId
!= JIM_BAD_FD
) {
1007 JimCloseFd(outputId
);
1009 inputId
= pipeIds
[0];
1010 pipeIds
[0] = pipeIds
[1] = JIM_BAD_FD
;
1012 *pidArrayPtr
= pidPtr
;
1015 * All done. Cleanup open files lying around and then return.
1019 if (inputId
!= JIM_BAD_FD
) {
1020 JimCloseFd(inputId
);
1022 if (lastOutputId
!= JIM_BAD_FD
) {
1023 JimCloseFd(lastOutputId
);
1025 if (errorId
!= JIM_BAD_FD
) {
1026 JimCloseFd(errorId
);
1028 Jim_Free(arg_array
);
1030 JimRestoreEnv(save_environ
);
1035 * An error occurred. There could have been extra files open, such
1036 * as pipes between children. Clean them all up. Detach any child
1037 * processes that have been created.
1041 if ((inPipePtr
!= NULL
) && (*inPipePtr
!= JIM_BAD_FD
)) {
1042 JimCloseFd(*inPipePtr
);
1043 *inPipePtr
= JIM_BAD_FD
;
1045 if ((outPipePtr
!= NULL
) && (*outPipePtr
!= JIM_BAD_FD
)) {
1046 JimCloseFd(*outPipePtr
);
1047 *outPipePtr
= JIM_BAD_FD
;
1049 if ((errFilePtr
!= NULL
) && (*errFilePtr
!= JIM_BAD_FD
)) {
1050 JimCloseFd(*errFilePtr
);
1051 *errFilePtr
= JIM_BAD_FD
;
1053 if (pipeIds
[0] != JIM_BAD_FD
) {
1054 JimCloseFd(pipeIds
[0]);
1056 if (pipeIds
[1] != JIM_BAD_FD
) {
1057 JimCloseFd(pipeIds
[1]);
1059 if (pidPtr
!= NULL
) {
1060 for (i
= 0; i
< numPids
; i
++) {
1061 if (pidPtr
[i
] != JIM_BAD_PID
) {
1062 JimDetachPids(interp
, 1, &pidPtr
[i
]);
1072 *----------------------------------------------------------------------
1074 * JimCleanupChildren --
1076 * This is a utility procedure used to wait for child processes
1077 * to exit, record information about abnormal exits, and then
1078 * collect any stderr output generated by them.
1081 * The return value is a standard Tcl result. If anything at
1082 * weird happened with the child processes, JIM_ERROR is returned
1083 * and a message is left in interp->result.
1086 * If the last character of interp->result is a newline, then it
1087 * is removed. File errorId gets closed, and pidPtr is freed
1088 * back to the storage allocator.
1090 *----------------------------------------------------------------------
1093 static int JimCleanupChildren(Jim_Interp
*interp
, int numPids
, pidtype
*pidPtr
, fdtype errorId
)
1095 struct WaitInfoTable
*table
= Jim_CmdPrivData(interp
);
1096 int result
= JIM_OK
;
1099 for (i
= 0; i
< numPids
; i
++) {
1101 if (JimWaitForProcess(table
, pidPtr
[i
], &waitStatus
) != JIM_BAD_PID
) {
1102 if (JimCheckWaitStatus(interp
, pidPtr
[i
], waitStatus
) != JIM_OK
) {
1110 * Read the standard error file. If there's anything there,
1111 * then add the file's contents to the result
1114 if (errorId
!= JIM_BAD_FD
) {
1115 JimRewindFd(errorId
);
1116 if (JimAppendStreamToString(interp
, errorId
, Jim_GetResult(interp
)) != JIM_OK
) {
1121 Jim_RemoveTrailingNewline(Jim_GetResult(interp
));
1126 int Jim_execInit(Jim_Interp
*interp
)
1128 if (Jim_PackageProvide(interp
, "exec", "1.0", JIM_ERRMSG
))
1133 * Disable SIGPIPE signals: if they were allowed, this process
1134 * might go away unexpectedly if children misbehave. This code
1135 * can potentially interfere with other application code that
1136 * expects to handle SIGPIPEs.
1138 * By doing this in the init function, applications can override
1139 * this later. Note that child processes have SIGPIPE restored
1140 * to the default after vfork().
1142 (void)signal(SIGPIPE
, SIG_IGN
);
1145 Jim_CreateCommand(interp
, "exec", Jim_ExecCmd
, JimAllocWaitInfoTable(), JimFreeWaitInfoTable
);
1149 #if defined(__MINGW32__)
1150 /* Windows-specific (mingw) implementation */
1152 static SECURITY_ATTRIBUTES
*JimStdSecAttrs(void)
1154 static SECURITY_ATTRIBUTES secAtts
;
1156 secAtts
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
1157 secAtts
.lpSecurityDescriptor
= NULL
;
1158 secAtts
.bInheritHandle
= TRUE
;
1162 static int JimErrno(void)
1164 switch (GetLastError()) {
1165 case ERROR_FILE_NOT_FOUND
: return ENOENT
;
1166 case ERROR_PATH_NOT_FOUND
: return ENOENT
;
1167 case ERROR_TOO_MANY_OPEN_FILES
: return EMFILE
;
1168 case ERROR_ACCESS_DENIED
: return EACCES
;
1169 case ERROR_INVALID_HANDLE
: return EBADF
;
1170 case ERROR_BAD_ENVIRONMENT
: return E2BIG
;
1171 case ERROR_BAD_FORMAT
: return ENOEXEC
;
1172 case ERROR_INVALID_ACCESS
: return EACCES
;
1173 case ERROR_INVALID_DRIVE
: return ENOENT
;
1174 case ERROR_CURRENT_DIRECTORY
: return EACCES
;
1175 case ERROR_NOT_SAME_DEVICE
: return EXDEV
;
1176 case ERROR_NO_MORE_FILES
: return ENOENT
;
1177 case ERROR_WRITE_PROTECT
: return EROFS
;
1178 case ERROR_BAD_UNIT
: return ENXIO
;
1179 case ERROR_NOT_READY
: return EBUSY
;
1180 case ERROR_BAD_COMMAND
: return EIO
;
1181 case ERROR_CRC
: return EIO
;
1182 case ERROR_BAD_LENGTH
: return EIO
;
1183 case ERROR_SEEK
: return EIO
;
1184 case ERROR_WRITE_FAULT
: return EIO
;
1185 case ERROR_READ_FAULT
: return EIO
;
1186 case ERROR_GEN_FAILURE
: return EIO
;
1187 case ERROR_SHARING_VIOLATION
: return EACCES
;
1188 case ERROR_LOCK_VIOLATION
: return EACCES
;
1189 case ERROR_SHARING_BUFFER_EXCEEDED
: return ENFILE
;
1190 case ERROR_HANDLE_DISK_FULL
: return ENOSPC
;
1191 case ERROR_NOT_SUPPORTED
: return ENODEV
;
1192 case ERROR_REM_NOT_LIST
: return EBUSY
;
1193 case ERROR_DUP_NAME
: return EEXIST
;
1194 case ERROR_BAD_NETPATH
: return ENOENT
;
1195 case ERROR_NETWORK_BUSY
: return EBUSY
;
1196 case ERROR_DEV_NOT_EXIST
: return ENODEV
;
1197 case ERROR_TOO_MANY_CMDS
: return EAGAIN
;
1198 case ERROR_ADAP_HDW_ERR
: return EIO
;
1199 case ERROR_BAD_NET_RESP
: return EIO
;
1200 case ERROR_UNEXP_NET_ERR
: return EIO
;
1201 case ERROR_NETNAME_DELETED
: return ENOENT
;
1202 case ERROR_NETWORK_ACCESS_DENIED
: return EACCES
;
1203 case ERROR_BAD_DEV_TYPE
: return ENODEV
;
1204 case ERROR_BAD_NET_NAME
: return ENOENT
;
1205 case ERROR_TOO_MANY_NAMES
: return ENFILE
;
1206 case ERROR_TOO_MANY_SESS
: return EIO
;
1207 case ERROR_SHARING_PAUSED
: return EAGAIN
;
1208 case ERROR_REDIR_PAUSED
: return EAGAIN
;
1209 case ERROR_FILE_EXISTS
: return EEXIST
;
1210 case ERROR_CANNOT_MAKE
: return ENOSPC
;
1211 case ERROR_OUT_OF_STRUCTURES
: return ENFILE
;
1212 case ERROR_ALREADY_ASSIGNED
: return EEXIST
;
1213 case ERROR_INVALID_PASSWORD
: return EPERM
;
1214 case ERROR_NET_WRITE_FAULT
: return EIO
;
1215 case ERROR_NO_PROC_SLOTS
: return EAGAIN
;
1216 case ERROR_DISK_CHANGE
: return EXDEV
;
1217 case ERROR_BROKEN_PIPE
: return EPIPE
;
1218 case ERROR_OPEN_FAILED
: return ENOENT
;
1219 case ERROR_DISK_FULL
: return ENOSPC
;
1220 case ERROR_NO_MORE_SEARCH_HANDLES
: return EMFILE
;
1221 case ERROR_INVALID_TARGET_HANDLE
: return EBADF
;
1222 case ERROR_INVALID_NAME
: return ENOENT
;
1223 case ERROR_PROC_NOT_FOUND
: return ESRCH
;
1224 case ERROR_WAIT_NO_CHILDREN
: return ECHILD
;
1225 case ERROR_CHILD_NOT_COMPLETE
: return ECHILD
;
1226 case ERROR_DIRECT_ACCESS_HANDLE
: return EBADF
;
1227 case ERROR_SEEK_ON_DEVICE
: return ESPIPE
;
1228 case ERROR_BUSY_DRIVE
: return EAGAIN
;
1229 case ERROR_DIR_NOT_EMPTY
: return EEXIST
;
1230 case ERROR_NOT_LOCKED
: return EACCES
;
1231 case ERROR_BAD_PATHNAME
: return ENOENT
;
1232 case ERROR_LOCK_FAILED
: return EACCES
;
1233 case ERROR_ALREADY_EXISTS
: return EEXIST
;
1234 case ERROR_FILENAME_EXCED_RANGE
: return ENAMETOOLONG
;
1235 case ERROR_BAD_PIPE
: return EPIPE
;
1236 case ERROR_PIPE_BUSY
: return EAGAIN
;
1237 case ERROR_PIPE_NOT_CONNECTED
: return EPIPE
;
1238 case ERROR_DIRECTORY
: return ENOTDIR
;
1243 static int JimPipe(fdtype pipefd
[2])
1245 if (CreatePipe(&pipefd
[0], &pipefd
[1], NULL
, 0)) {
1251 static fdtype
JimDupFd(fdtype infd
)
1254 pidtype pid
= GetCurrentProcess();
1256 if (DuplicateHandle(pid
, infd
, pid
, &dupfd
, 0, TRUE
, DUPLICATE_SAME_ACCESS
)) {
1262 static int JimRewindFd(fdtype fd
)
1264 return SetFilePointer(fd
, 0, NULL
, FILE_BEGIN
) == INVALID_SET_FILE_POINTER
? -1 : 0;
1268 static int JimReadFd(fdtype fd
, char *buffer
, size_t len
)
1272 if (ReadFile(fd
, buffer
, len
, &num
, NULL
)) {
1275 if (GetLastError() == ERROR_HANDLE_EOF
|| GetLastError() == ERROR_BROKEN_PIPE
) {
1282 static FILE *JimFdOpenForRead(fdtype fd
)
1284 return _fdopen(_open_osfhandle((int)fd
, _O_RDONLY
| _O_TEXT
), "r");
1287 static fdtype
JimFileno(FILE *fh
)
1289 return (fdtype
)_get_osfhandle(_fileno(fh
));
1292 static fdtype
JimOpenForRead(const char *filename
)
1294 return CreateFile(filename
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1295 JimStdSecAttrs(), OPEN_EXISTING
, 0, NULL
);
1298 static fdtype
JimOpenForWrite(const char *filename
, int append
)
1300 return CreateFile(filename
, append
? FILE_APPEND_DATA
: GENERIC_WRITE
, FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1301 JimStdSecAttrs(), append
? OPEN_ALWAYS
: CREATE_ALWAYS
, 0, (HANDLE
) NULL
);
1304 static FILE *JimFdOpenForWrite(fdtype fd
)
1306 return _fdopen(_open_osfhandle((int)fd
, _O_TEXT
), "w");
1309 static pidtype
JimWaitPid(pidtype pid
, int *status
, int nohang
)
1311 DWORD ret
= WaitForSingleObject(pid
, nohang
? 0 : INFINITE
);
1312 if (ret
== WAIT_TIMEOUT
|| ret
== WAIT_FAILED
) {
1313 /* WAIT_TIMEOUT can only happend with WNOHANG */
1316 GetExitCodeProcess(pid
, &ret
);
1322 static HANDLE
JimCreateTemp(Jim_Interp
*interp
, const char *contents
, int len
)
1324 char name
[MAX_PATH
];
1327 if (!GetTempPath(MAX_PATH
, name
) || !GetTempFileName(name
, "JIM", 0, name
)) {
1331 handle
= CreateFile(name
, GENERIC_READ
| GENERIC_WRITE
, 0, JimStdSecAttrs(),
1332 CREATE_ALWAYS
, FILE_ATTRIBUTE_TEMPORARY
| FILE_FLAG_DELETE_ON_CLOSE
,
1335 if (handle
== INVALID_HANDLE_VALUE
) {
1339 if (contents
!= NULL
) {
1340 /* Use fdopen() to get automatic text-mode translation */
1341 FILE *fh
= JimFdOpenForWrite(JimDupFd(handle
));
1346 if (fwrite(contents
, len
, 1, fh
) != 1) {
1350 fseek(fh
, 0, SEEK_SET
);
1356 Jim_SetResultErrno(interp
, "failed to create temp file");
1357 CloseHandle(handle
);
1363 JimWinFindExecutable(const char *originalName
, char fullPath
[MAX_PATH
])
1366 static char extensions
[][5] = {".exe", "", ".bat"};
1368 for (i
= 0; i
< (int) (sizeof(extensions
) / sizeof(extensions
[0])); i
++) {
1369 lstrcpyn(fullPath
, originalName
, MAX_PATH
- 5);
1370 lstrcat(fullPath
, extensions
[i
]);
1372 if (SearchPath(NULL
, fullPath
, NULL
, MAX_PATH
, fullPath
, NULL
) == 0) {
1375 if (GetFileAttributes(fullPath
) & FILE_ATTRIBUTE_DIRECTORY
) {
1384 static char **JimSaveEnv(char **env
)
1389 static void JimRestoreEnv(char **env
)
1391 JimFreeEnv(env
, Jim_GetEnviron());
1395 JimWinBuildCommandLine(Jim_Interp
*interp
, char **argv
)
1397 char *start
, *special
;
1400 Jim_Obj
*strObj
= Jim_NewStringObj(interp
, "", 0);
1402 for (i
= 0; argv
[i
]; i
++) {
1404 Jim_AppendString(interp
, strObj
, " ", 1);
1407 if (argv
[i
][0] == '\0') {
1412 for (start
= argv
[i
]; *start
!= '\0'; start
++) {
1413 if (isspace(UCHAR(*start
))) {
1420 Jim_AppendString(interp
, strObj
, "\"" , 1);
1424 for (special
= argv
[i
]; ; ) {
1425 if ((*special
== '\\') && (special
[1] == '\\' ||
1426 special
[1] == '"' || (quote
&& special
[1] == '\0'))) {
1427 Jim_AppendString(interp
, strObj
, start
, special
- start
);
1431 if (*special
== '"' || (quote
&& *special
== '\0')) {
1433 * N backslashes followed a quote -> insert
1434 * N * 2 + 1 backslashes then a quote.
1437 Jim_AppendString(interp
, strObj
, start
, special
- start
);
1440 if (*special
!= '\\') {
1444 Jim_AppendString(interp
, strObj
, start
, special
- start
);
1447 if (*special
== '"') {
1448 if (special
== start
) {
1449 Jim_AppendString(interp
, strObj
, "\"", 1);
1452 Jim_AppendString(interp
, strObj
, start
, special
- start
);
1454 Jim_AppendString(interp
, strObj
, "\\\"", 2);
1455 start
= special
+ 1;
1457 if (*special
== '\0') {
1462 Jim_AppendString(interp
, strObj
, start
, special
- start
);
1464 Jim_AppendString(interp
, strObj
, "\"", 1);
1471 JimStartWinProcess(Jim_Interp
*interp
, char **argv
, char *env
, fdtype inputId
, fdtype outputId
, fdtype errorId
)
1473 STARTUPINFO startInfo
;
1474 PROCESS_INFORMATION procInfo
;
1476 char execPath
[MAX_PATH
];
1477 pidtype pid
= JIM_BAD_PID
;
1478 Jim_Obj
*cmdLineObj
;
1480 if (JimWinFindExecutable(argv
[0], execPath
) < 0) {
1485 hProcess
= GetCurrentProcess();
1486 cmdLineObj
= JimWinBuildCommandLine(interp
, argv
);
1489 * STARTF_USESTDHANDLES must be used to pass handles to child process.
1490 * Using SetStdHandle() and/or dup2() only works when a console mode
1491 * parent process is spawning an attached console mode child process.
1494 ZeroMemory(&startInfo
, sizeof(startInfo
));
1495 startInfo
.cb
= sizeof(startInfo
);
1496 startInfo
.dwFlags
= STARTF_USESTDHANDLES
;
1497 startInfo
.hStdInput
= INVALID_HANDLE_VALUE
;
1498 startInfo
.hStdOutput
= INVALID_HANDLE_VALUE
;
1499 startInfo
.hStdError
= INVALID_HANDLE_VALUE
;
1502 * Duplicate all the handles which will be passed off as stdin, stdout
1503 * and stderr of the child process. The duplicate handles are set to
1504 * be inheritable, so the child process can use them.
1506 if (inputId
== JIM_BAD_FD
) {
1507 if (CreatePipe(&startInfo
.hStdInput
, &h
, JimStdSecAttrs(), 0) != FALSE
) {
1511 DuplicateHandle(hProcess
, inputId
, hProcess
, &startInfo
.hStdInput
,
1512 0, TRUE
, DUPLICATE_SAME_ACCESS
);
1514 if (startInfo
.hStdInput
== JIM_BAD_FD
) {
1518 if (outputId
== JIM_BAD_FD
) {
1519 startInfo
.hStdOutput
= CreateFile("NUL:", GENERIC_WRITE
, 0,
1520 JimStdSecAttrs(), OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
1522 DuplicateHandle(hProcess
, outputId
, hProcess
, &startInfo
.hStdOutput
,
1523 0, TRUE
, DUPLICATE_SAME_ACCESS
);
1525 if (startInfo
.hStdOutput
== JIM_BAD_FD
) {
1529 if (errorId
== JIM_BAD_FD
) {
1531 * If handle was not set, errors should be sent to an infinitely
1535 startInfo
.hStdError
= CreateFile("NUL:", GENERIC_WRITE
, 0,
1536 JimStdSecAttrs(), OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
1538 DuplicateHandle(hProcess
, errorId
, hProcess
, &startInfo
.hStdError
,
1539 0, TRUE
, DUPLICATE_SAME_ACCESS
);
1541 if (startInfo
.hStdError
== JIM_BAD_FD
) {
1545 if (!CreateProcess(NULL
, (char *)Jim_String(cmdLineObj
), NULL
, NULL
, TRUE
,
1546 0, env
, NULL
, &startInfo
, &procInfo
)) {
1551 * "When an application spawns a process repeatedly, a new thread
1552 * instance will be created for each process but the previous
1553 * instances may not be cleaned up. This results in a significant
1554 * virtual memory loss each time the process is spawned. If there
1555 * is a WaitForInputIdle() call between CreateProcess() and
1556 * CloseHandle(), the problem does not occur." PSS ID Number: Q124121
1559 WaitForInputIdle(procInfo
.hProcess
, 5000);
1560 CloseHandle(procInfo
.hThread
);
1562 pid
= procInfo
.hProcess
;
1565 Jim_FreeNewObj(interp
, cmdLineObj
);
1566 if (startInfo
.hStdInput
!= JIM_BAD_FD
) {
1567 CloseHandle(startInfo
.hStdInput
);
1569 if (startInfo
.hStdOutput
!= JIM_BAD_FD
) {
1570 CloseHandle(startInfo
.hStdOutput
);
1572 if (startInfo
.hStdError
!= JIM_BAD_FD
) {
1573 CloseHandle(startInfo
.hStdError
);
1578 /* Unix-specific implementation */
1579 static int JimOpenForWrite(const char *filename
, int append
)
1581 return open(filename
, O_WRONLY
| O_CREAT
| (append
? O_APPEND
: O_TRUNC
), 0666);
1584 static int JimRewindFd(int fd
)
1586 return lseek(fd
, 0L, SEEK_SET
);
1589 static int JimCreateTemp(Jim_Interp
*interp
, const char *contents
, int len
)
1591 char inName
[] = "/tmp/tcl.tmp.XXXXXX";
1593 int fd
= mkstemp(inName
);
1594 if (fd
== JIM_BAD_FD
) {
1595 Jim_SetResultErrno(interp
, "couldn't create temp file");
1600 if (write(fd
, contents
, len
) != len
) {
1601 Jim_SetResultErrno(interp
, "couldn't write temp file");
1605 lseek(fd
, 0L, SEEK_SET
);
1610 static char **JimSaveEnv(char **env
)
1612 char **saveenv
= Jim_GetEnviron();
1613 Jim_SetEnviron(env
);
1617 static void JimRestoreEnv(char **env
)
1619 JimFreeEnv(Jim_GetEnviron(), env
);
1620 Jim_SetEnviron(env
);