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
))
85 Jim_CreateCommand(interp
, "exec", Jim_ExecCmd
, NULL
, NULL
);
89 /* Full exec implementation for unix and mingw */
94 #if defined(__MINGW32__)
95 /* XXX: Should we use this implementation for cygwin too? msvc? */
99 #define WIN32_LEAN_AND_MEAN
103 typedef HANDLE fdtype
;
104 typedef HANDLE pidtype
;
105 #define JIM_BAD_FD INVALID_HANDLE_VALUE
106 #define JIM_BAD_PID INVALID_HANDLE_VALUE
107 #define JimCloseFd CloseHandle
109 #define WIFEXITED(STATUS) 1
110 #define WEXITSTATUS(STATUS) (STATUS)
111 #define WIFSIGNALED(STATUS) 0
112 #define WTERMSIG(STATUS) 0
115 static fdtype
JimFileno(FILE *fh
);
116 static pidtype
JimWaitPid(pidtype pid
, int *status
, int nohang
);
117 static fdtype
JimDupFd(fdtype infd
);
118 static fdtype
JimOpenForRead(const char *filename
);
119 static FILE *JimFdOpenForRead(fdtype fd
);
120 static int JimPipe(fdtype pipefd
[2]);
121 static pidtype
JimStartWinProcess(Jim_Interp
*interp
, char **argv
, char *env
,
122 fdtype inputId
, fdtype outputId
, fdtype errorId
);
123 static int JimErrno(void);
125 #include "jim-signal.h"
128 #include <sys/wait.h>
133 #define JimErrno() errno
134 #define JIM_BAD_FD -1
135 #define JIM_BAD_PID -1
136 #define JimFileno fileno
137 #define JimReadFd read
138 #define JimCloseFd close
139 #define JimWaitPid waitpid
141 #define JimFdOpenForRead(FD) fdopen((FD), "r")
142 #define JimOpenForRead(NAME) open((NAME), O_RDONLY, 0)
145 #define execvpe(ARG0, ARGV, ENV) execvp(ARG0, ARGV)
149 static const char *JimStrError(void);
150 static char **JimSaveEnv(char **env
);
151 static void JimRestoreEnv(char **env
);
152 static int JimCreatePipeline(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
,
153 pidtype
**pidArrayPtr
, fdtype
*inPipePtr
, fdtype
*outPipePtr
, fdtype
*errFilePtr
);
154 static void JimDetachPids(Jim_Interp
*interp
, int numPids
, const pidtype
*pidPtr
);
155 static int JimCleanupChildren(Jim_Interp
*interp
, int numPids
, pidtype
*pidPtr
, fdtype errorId
);
156 static fdtype
JimCreateTemp(Jim_Interp
*interp
, const char *contents
, int len
);
157 static fdtype
JimOpenForWrite(const char *filename
, int append
);
158 static int JimRewindFd(fdtype fd
);
160 static void Jim_SetResultErrno(Jim_Interp
*interp
, const char *msg
)
162 Jim_SetResultFormatted(interp
, "%s: %s", msg
, JimStrError());
165 static const char *JimStrError(void)
167 return strerror(JimErrno());
171 * If the last character of 'objPtr' is a newline, then remove
172 * the newline character.
174 static void Jim_RemoveTrailingNewline(Jim_Obj
*objPtr
)
177 const char *s
= Jim_GetString(objPtr
, &len
);
179 if (len
> 0 && s
[len
- 1] == '\n') {
181 objPtr
->bytes
[objPtr
->length
] = '\0';
186 * Read from 'fd', append the data to strObj and close 'fd'.
187 * Returns JIM_OK if OK, or JIM_ERR on error.
189 static int JimAppendStreamToString(Jim_Interp
*interp
, fdtype fd
, Jim_Obj
*strObj
)
192 FILE *fh
= JimFdOpenForRead(fd
);
198 int retval
= fread(buf
, 1, sizeof(buf
), fh
);
200 Jim_AppendString(interp
, strObj
, buf
, retval
);
202 if (retval
!= sizeof(buf
)) {
206 Jim_RemoveTrailingNewline(strObj
);
212 * Builds the environment array from $::env
214 * If $::env is not set, simply returns environ.
216 * Otherwise allocates the environ array from the contents of $::env
218 * If the exec fails, memory can be freed via JimFreeEnv()
220 static char **JimBuildEnv(Jim_Interp
*interp
)
229 Jim_Obj
*objPtr
= Jim_GetGlobalVariableStr(interp
, "env", JIM_NONE
);
232 return Jim_GetEnviron();
235 /* We build the array as a single block consisting of the pointers followed by
236 * the strings. This has the advantage of being easy to allocate/free and being
237 * compatible with both unix and windows
240 /* Calculate the required size */
241 num
= Jim_ListLength(interp
, objPtr
);
243 /* Silently drop the last element if not a valid dictionary */
246 /* We need one \0 and one equal sign for each element.
247 * A list has at least one space for each element except the first.
248 * We need one extra char for the extra null terminator and one for the equal sign.
250 size
= Jim_Length(objPtr
) + 2;
252 envptr
= Jim_Alloc(sizeof(*envptr
) * (num
/ 2 + 1) + size
);
253 envdata
= (char *)&envptr
[num
/ 2 + 1];
256 for (i
= 0; i
< num
; i
+= 2) {
260 Jim_ListIndex(interp
, objPtr
, i
, &elemObj
, JIM_NONE
);
261 s1
= Jim_String(elemObj
);
262 Jim_ListIndex(interp
, objPtr
, i
+ 1, &elemObj
, JIM_NONE
);
263 s2
= Jim_String(elemObj
);
266 envdata
+= sprintf(envdata
, "%s=%s", s1
, s2
);
277 * Frees the environment allocated by JimBuildEnv()
279 * Must pass original_environ.
281 static void JimFreeEnv(char **env
, char **original_environ
)
283 if (env
!= original_environ
) {
289 * Create and store an appropriate value for the global variable $::errorCode
290 * Based on pid and waitStatus.
292 * Returns JIM_OK for a normal exit with code 0, otherwise returns JIM_ERR.
294 static int JimCheckWaitStatus(Jim_Interp
*interp
, pidtype pid
, int waitStatus
)
296 Jim_Obj
*errorCode
= Jim_NewListObj(interp
, NULL
, 0);
299 if (WIFEXITED(waitStatus
)) {
300 if (WEXITSTATUS(waitStatus
) == 0) {
301 Jim_ListAppendElement(interp
, errorCode
, Jim_NewStringObj(interp
, "NONE", -1));
305 Jim_ListAppendElement(interp
, errorCode
, Jim_NewStringObj(interp
, "CHILDSTATUS", -1));
306 Jim_ListAppendElement(interp
, errorCode
, Jim_NewIntObj(interp
, (long)pid
));
307 Jim_ListAppendElement(interp
, errorCode
, Jim_NewIntObj(interp
, WEXITSTATUS(waitStatus
)));
314 if (WIFSIGNALED(waitStatus
)) {
315 type
= "CHILDKILLED";
320 action
= "suspended";
323 Jim_ListAppendElement(interp
, errorCode
, Jim_NewStringObj(interp
, type
, -1));
325 #ifdef jim_ext_signal
326 Jim_SetResultFormatted(interp
, "child %s by signal %s", action
, Jim_SignalId(WTERMSIG(waitStatus
)));
327 Jim_ListAppendElement(interp
, errorCode
, Jim_NewStringObj(interp
, Jim_SignalId(WTERMSIG(waitStatus
)), -1));
328 Jim_ListAppendElement(interp
, errorCode
, Jim_NewIntObj(interp
, pid
));
329 Jim_ListAppendElement(interp
, errorCode
, Jim_NewStringObj(interp
, Jim_SignalName(WTERMSIG(waitStatus
)), -1));
331 Jim_SetResultFormatted(interp
, "child %s by signal %d", action
, WTERMSIG(waitStatus
));
332 Jim_ListAppendElement(interp
, errorCode
, Jim_NewIntObj(interp
, WTERMSIG(waitStatus
)));
333 Jim_ListAppendElement(interp
, errorCode
, Jim_NewIntObj(interp
, (long)pid
));
334 Jim_ListAppendElement(interp
, errorCode
, Jim_NewIntObj(interp
, WTERMSIG(waitStatus
)));
337 Jim_SetGlobalVariableStr(interp
, "errorCode", errorCode
);
342 * Data structures of the following type are used by JimFork and
343 * JimWaitPids to keep track of child processes.
348 pidtype pid
; /* Process id of child. */
349 int status
; /* Status returned when child exited or suspended. */
350 int flags
; /* Various flag bits; see below for definitions. */
353 struct WaitInfoTable
{
354 struct WaitInfo
*info
; /* Table of outstanding processes */
355 int size
; /* Size of the allocated table */
356 int used
; /* Number of entries in use */
360 * Flag bits in WaitInfo structures:
362 * WI_DETACHED - Non-zero means no-one cares about the
363 * process anymore. Ignore it until it
364 * exits, then forget about it.
367 #define WI_DETACHED 2
369 #define WAIT_TABLE_GROW_BY 4
371 static void JimFreeWaitInfoTable(struct Jim_Interp
*interp
, void *privData
)
373 struct WaitInfoTable
*table
= privData
;
375 Jim_Free(table
->info
);
379 static struct WaitInfoTable
*JimAllocWaitInfoTable(void)
381 struct WaitInfoTable
*table
= Jim_Alloc(sizeof(*table
));
383 table
->size
= table
->used
= 0;
389 * The main [exec] command
391 static int Jim_ExecCmd(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
393 fdtype outputId
; /* File id for output pipe. -1 means command overrode. */
394 fdtype errorId
; /* File id for temporary file containing error output. */
399 * See if the command is to be run in the 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 * Indicates that one or more child processes have been placed in
512 * background and are no longer cared about.
513 * These children can be cleaned up with JimReapDetachedPids().
515 static void JimDetachPids(Jim_Interp
*interp
, int numPids
, const pidtype
*pidPtr
)
518 struct WaitInfoTable
*table
= Jim_CmdPrivData(interp
);
520 for (j
= 0; j
< numPids
; j
++) {
521 /* Find it in the table */
523 for (i
= 0; i
< table
->used
; i
++) {
524 if (pidPtr
[j
] == table
->info
[i
].pid
) {
525 table
->info
[i
].flags
|= WI_DETACHED
;
532 static FILE *JimGetAioFilehandle(Jim_Interp
*interp
, const char *name
)
537 fhObj
= Jim_NewStringObj(interp
, name
, -1);
538 Jim_IncrRefCount(fhObj
);
539 fh
= Jim_AioFilehandle(interp
, fhObj
);
540 Jim_DecrRefCount(interp
, fhObj
);
546 *----------------------------------------------------------------------
548 * JimCreatePipeline --
550 * Given an argc/argv array, instantiate a pipeline of processes
551 * as described by the argv.
554 * The return value is a count of the number of new processes
555 * created, or -1 if an error occurred while creating the pipeline.
556 * *pidArrayPtr is filled in with the address of a dynamically
557 * allocated array giving the ids of all of the processes. It
558 * is up to the caller to free this array when it isn't needed
559 * anymore. If inPipePtr is non-NULL, *inPipePtr is filled in
560 * with the file id for the input pipe for the pipeline (if any):
561 * the caller must eventually close this file. If outPipePtr
562 * isn't NULL, then *outPipePtr is filled in with the file id
563 * for the output pipe from the pipeline: the caller must close
564 * this file. If errFilePtr isn't NULL, then *errFilePtr is filled
565 * with a file id that may be used to read error output after the
566 * pipeline completes.
569 * Processes and pipes are created.
571 *----------------------------------------------------------------------
574 JimCreatePipeline(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, pidtype
**pidArrayPtr
,
575 fdtype
*inPipePtr
, fdtype
*outPipePtr
, fdtype
*errFilePtr
)
577 pidtype
*pidPtr
= NULL
; /* Points to malloc-ed array holding all
578 * the pids of child processes. */
579 int numPids
= 0; /* Actual number of processes that exist
580 * at *pidPtr right now. */
581 int cmdCount
; /* Count of number of distinct commands
582 * found in argc/argv. */
583 const char *input
= NULL
; /* Describes input for pipeline, depending
584 * on "inputFile". NULL means take input
585 * from stdin/pipe. */
586 int input_len
= 0; /* Length of input, if relevant */
588 #define FILE_NAME 0 /* input/output: filename */
589 #define FILE_APPEND 1 /* output only: filename, append */
590 #define FILE_HANDLE 2 /* input/output: filehandle */
591 #define FILE_TEXT 3 /* input only: input is actual text */
593 int inputFile
= FILE_NAME
; /* 1 means input is name of input file.
594 * 2 means input is filehandle name.
595 * 0 means input holds actual
596 * text to be input to command. */
598 int outputFile
= FILE_NAME
; /* 0 means output is the name of output file.
599 * 1 means output is the name of output file, and append.
600 * 2 means output is filehandle name.
601 * All this is ignored if output is NULL
603 int errorFile
= FILE_NAME
; /* 0 means error is the name of error file.
604 * 1 means error is the name of error file, and append.
605 * 2 means error is filehandle name.
606 * All this is ignored if error is NULL
608 const char *output
= NULL
; /* Holds name of output file to pipe to,
609 * or NULL if output goes to stdout/pipe. */
610 const char *error
= NULL
; /* Holds name of stderr file to pipe to,
611 * or NULL if stderr goes to stderr/pipe. */
612 fdtype inputId
= JIM_BAD_FD
;
613 /* Readable file id input to current command in
614 * pipeline (could be file or pipe). JIM_BAD_FD
615 * means use stdin. */
616 fdtype outputId
= JIM_BAD_FD
;
617 /* Writable file id for output from current
618 * command in pipeline (could be file or pipe).
619 * JIM_BAD_FD means use stdout. */
620 fdtype errorId
= JIM_BAD_FD
;
621 /* Writable file id for all standard error
622 * output from all commands in pipeline. JIM_BAD_FD
623 * means use stderr. */
624 fdtype lastOutputId
= JIM_BAD_FD
;
625 /* Write file id for output from last command
626 * in pipeline (could be file or pipe).
627 * -1 means use stdout. */
628 fdtype pipeIds
[2]; /* File ids for pipe that's being created. */
629 int firstArg
, lastArg
; /* Indexes of first and last arguments in
630 * current command. */
635 struct WaitInfoTable
*table
= Jim_CmdPrivData(interp
);
637 /* Holds the args which will be used to exec */
638 char **arg_array
= Jim_Alloc(sizeof(*arg_array
) * (argc
+ 1));
641 JimReapDetachedPids(table
);
643 if (inPipePtr
!= NULL
) {
644 *inPipePtr
= JIM_BAD_FD
;
646 if (outPipePtr
!= NULL
) {
647 *outPipePtr
= JIM_BAD_FD
;
649 if (errFilePtr
!= NULL
) {
650 *errFilePtr
= JIM_BAD_FD
;
652 pipeIds
[0] = pipeIds
[1] = JIM_BAD_FD
;
655 * First, scan through all the arguments to figure out the structure
656 * of the pipeline. Count the number of distinct processes (it's the
657 * number of "|" arguments). If there are "<", "<<", or ">" arguments
658 * then make note of input and output redirection and remove these
659 * arguments and the arguments that follow them.
663 for (i
= 0; i
< argc
; i
++) {
664 const char *arg
= Jim_String(argv
[i
]);
667 inputFile
= FILE_NAME
;
670 inputFile
= FILE_TEXT
;
671 input_len
= Jim_Length(argv
[i
]) - 2;
674 else if (*input
== '@') {
675 inputFile
= FILE_HANDLE
;
679 if (!*input
&& ++i
< argc
) {
680 input
= Jim_GetString(argv
[i
], &input_len
);
683 else if (arg
[0] == '>') {
686 outputFile
= FILE_NAME
;
689 if (*output
== '>') {
690 outputFile
= FILE_APPEND
;
693 if (*output
== '&') {
694 /* Redirect stderr too */
698 if (*output
== '@') {
699 outputFile
= FILE_HANDLE
;
702 if (!*output
&& ++i
< argc
) {
703 output
= Jim_String(argv
[i
]);
706 errorFile
= outputFile
;
710 else if (arg
[0] == '2' && arg
[1] == '>') {
712 errorFile
= FILE_NAME
;
715 errorFile
= FILE_HANDLE
;
718 else if (*error
== '>') {
719 errorFile
= FILE_APPEND
;
722 if (!*error
&& ++i
< argc
) {
723 error
= Jim_String(argv
[i
]);
727 if (strcmp(arg
, "|") == 0 || strcmp(arg
, "|&") == 0) {
728 if (i
== lastBar
+ 1 || i
== argc
- 1) {
729 Jim_SetResultString(interp
, "illegal use of | or |& in command", -1);
735 /* Either |, |& or a "normal" arg, so store it in the arg array */
736 arg_array
[arg_count
++] = (char *)arg
;
741 Jim_SetResultFormatted(interp
, "can't specify \"%s\" as last word in command", arg
);
746 if (arg_count
== 0) {
747 Jim_SetResultString(interp
, "didn't specify command to execute", -1);
753 /* Must do this before vfork(), so do it now */
754 save_environ
= JimSaveEnv(JimBuildEnv(interp
));
757 * Set up the redirected input source for the pipeline, if
761 if (inputFile
== FILE_TEXT
) {
763 * Immediate data in command. Create temporary file and
764 * put data into file.
766 inputId
= JimCreateTemp(interp
, input
, input_len
);
767 if (inputId
== JIM_BAD_FD
) {
771 else if (inputFile
== FILE_HANDLE
) {
772 /* Should be a file descriptor */
773 FILE *fh
= JimGetAioFilehandle(interp
, input
);
778 inputId
= JimDupFd(JimFileno(fh
));
782 * File redirection. Just open the file.
784 inputId
= JimOpenForRead(input
);
785 if (inputId
== JIM_BAD_FD
) {
786 Jim_SetResultFormatted(interp
, "couldn't read file \"%s\": %s", input
, JimStrError());
791 else if (inPipePtr
!= NULL
) {
792 if (JimPipe(pipeIds
) != 0) {
793 Jim_SetResultErrno(interp
, "couldn't create input pipe for command");
796 inputId
= pipeIds
[0];
797 *inPipePtr
= pipeIds
[1];
798 pipeIds
[0] = pipeIds
[1] = JIM_BAD_FD
;
802 * Set up the redirected output sink for the pipeline from one
803 * of two places, if requested.
805 if (output
!= NULL
) {
806 if (outputFile
== FILE_HANDLE
) {
807 FILE *fh
= JimGetAioFilehandle(interp
, output
);
812 lastOutputId
= JimDupFd(JimFileno(fh
));
816 * Output is to go to a file.
818 lastOutputId
= JimOpenForWrite(output
, outputFile
== FILE_APPEND
);
819 if (lastOutputId
== JIM_BAD_FD
) {
820 Jim_SetResultFormatted(interp
, "couldn't write file \"%s\": %s", output
, JimStrError());
825 else if (outPipePtr
!= NULL
) {
827 * Output is to go to a pipe.
829 if (JimPipe(pipeIds
) != 0) {
830 Jim_SetResultErrno(interp
, "couldn't create output pipe");
833 lastOutputId
= pipeIds
[1];
834 *outPipePtr
= pipeIds
[0];
835 pipeIds
[0] = pipeIds
[1] = JIM_BAD_FD
;
837 /* If we are redirecting stderr with 2>filename or 2>@fileId, then we ignore errFilePtr */
839 if (errorFile
== FILE_HANDLE
) {
840 if (strcmp(error
, "1") == 0) {
842 if (lastOutputId
!= JIM_BAD_FD
) {
843 errorId
= JimDupFd(lastOutputId
);
846 /* No redirection of stdout, so just use 2>@stdout */
850 if (errorId
== JIM_BAD_FD
) {
851 FILE *fh
= JimGetAioFilehandle(interp
, error
);
856 errorId
= JimDupFd(JimFileno(fh
));
861 * Output is to go to a file.
863 errorId
= JimOpenForWrite(error
, errorFile
== FILE_APPEND
);
864 if (errorId
== JIM_BAD_FD
) {
865 Jim_SetResultFormatted(interp
, "couldn't write file \"%s\": %s", error
, JimStrError());
870 else if (errFilePtr
!= NULL
) {
872 * Set up the standard error output sink for the pipeline, if
873 * requested. Use a temporary file which is opened, then deleted.
874 * Could potentially just use pipe, but if it filled up it could
875 * cause the pipeline to deadlock: we'd be waiting for processes
876 * to complete before reading stderr, and processes couldn't complete
877 * because stderr was backed up.
879 errorId
= JimCreateTemp(interp
, NULL
, 0);
880 if (errorId
== JIM_BAD_FD
) {
883 *errFilePtr
= JimDupFd(errorId
);
887 * Scan through the argc array, forking off a process for each
888 * group of arguments between "|" arguments.
891 pidPtr
= Jim_Alloc(cmdCount
* sizeof(*pidPtr
));
892 for (i
= 0; i
< numPids
; i
++) {
893 pidPtr
[i
] = JIM_BAD_PID
;
895 for (firstArg
= 0; firstArg
< arg_count
; numPids
++, firstArg
= lastArg
+ 1) {
896 int pipe_dup_err
= 0;
897 fdtype origErrorId
= errorId
;
899 for (lastArg
= firstArg
; lastArg
< arg_count
; lastArg
++) {
900 if (arg_array
[lastArg
][0] == '|') {
901 if (arg_array
[lastArg
][1] == '&') {
907 /* Replace | with NULL for execv() */
908 arg_array
[lastArg
] = NULL
;
909 if (lastArg
== arg_count
) {
910 outputId
= lastOutputId
;
913 if (JimPipe(pipeIds
) != 0) {
914 Jim_SetResultErrno(interp
, "couldn't create pipe");
917 outputId
= pipeIds
[1];
920 /* Need to do this befor vfork() */
925 /* Now fork the child */
928 pid
= JimStartWinProcess(interp
, &arg_array
[firstArg
], save_environ
? save_environ
[0] : NULL
, inputId
, outputId
, errorId
);
929 if (pid
== JIM_BAD_PID
) {
930 Jim_SetResultFormatted(interp
, "couldn't exec \"%s\"", arg_array
[firstArg
]);
935 * Make a new process and enter it into the table if the fork
940 Jim_SetResultErrno(interp
, "couldn't fork child process");
946 if (inputId
!= -1) dup2(inputId
, 0);
947 if (outputId
!= -1) dup2(outputId
, 1);
948 if (errorId
!= -1) dup2(errorId
, 2);
950 for (i
= 3; (i
<= outputId
) || (i
<= inputId
) || (i
<= errorId
); i
++) {
954 /* Restore SIGPIPE behaviour */
955 (void)signal(SIGPIPE
, SIG_DFL
);
957 execvpe(arg_array
[firstArg
], &arg_array
[firstArg
], Jim_GetEnviron());
959 /* Need to prep an error message before vfork(), just in case */
960 fprintf(stderr
, "couldn't exec \"%s\"\n", arg_array
[firstArg
]);
968 * Enlarge the wait table if there isn't enough space for a new
971 if (table
->used
== table
->size
) {
972 table
->size
+= WAIT_TABLE_GROW_BY
;
973 table
->info
= Jim_Realloc(table
->info
, table
->size
* sizeof(*table
->info
));
976 table
->info
[table
->used
].pid
= pid
;
977 table
->info
[table
->used
].flags
= 0;
980 pidPtr
[numPids
] = pid
;
982 /* Restore in case of pipe_dup_err */
983 errorId
= origErrorId
;
986 * Close off our copies of file descriptors that were set up for
987 * this child, then set up the input for the next child.
990 if (inputId
!= JIM_BAD_FD
) {
993 if (outputId
!= JIM_BAD_FD
) {
994 JimCloseFd(outputId
);
996 inputId
= pipeIds
[0];
997 pipeIds
[0] = pipeIds
[1] = JIM_BAD_FD
;
999 *pidArrayPtr
= pidPtr
;
1002 * All done. Cleanup open files lying around and then return.
1006 if (inputId
!= JIM_BAD_FD
) {
1007 JimCloseFd(inputId
);
1009 if (lastOutputId
!= JIM_BAD_FD
) {
1010 JimCloseFd(lastOutputId
);
1012 if (errorId
!= JIM_BAD_FD
) {
1013 JimCloseFd(errorId
);
1015 Jim_Free(arg_array
);
1017 JimRestoreEnv(save_environ
);
1022 * An error occurred. There could have been extra files open, such
1023 * as pipes between children. Clean them all up. Detach any child
1024 * processes that have been created.
1028 if ((inPipePtr
!= NULL
) && (*inPipePtr
!= JIM_BAD_FD
)) {
1029 JimCloseFd(*inPipePtr
);
1030 *inPipePtr
= JIM_BAD_FD
;
1032 if ((outPipePtr
!= NULL
) && (*outPipePtr
!= JIM_BAD_FD
)) {
1033 JimCloseFd(*outPipePtr
);
1034 *outPipePtr
= JIM_BAD_FD
;
1036 if ((errFilePtr
!= NULL
) && (*errFilePtr
!= JIM_BAD_FD
)) {
1037 JimCloseFd(*errFilePtr
);
1038 *errFilePtr
= JIM_BAD_FD
;
1040 if (pipeIds
[0] != JIM_BAD_FD
) {
1041 JimCloseFd(pipeIds
[0]);
1043 if (pipeIds
[1] != JIM_BAD_FD
) {
1044 JimCloseFd(pipeIds
[1]);
1046 if (pidPtr
!= NULL
) {
1047 for (i
= 0; i
< numPids
; i
++) {
1048 if (pidPtr
[i
] != JIM_BAD_PID
) {
1049 JimDetachPids(interp
, 1, &pidPtr
[i
]);
1059 *----------------------------------------------------------------------
1061 * JimCleanupChildren --
1063 * This is a utility procedure used to wait for child processes
1064 * to exit, record information about abnormal exits, and then
1065 * collect any stderr output generated by them.
1068 * The return value is a standard Tcl result. If anything at
1069 * weird happened with the child processes, JIM_ERROR is returned
1070 * and a message is left in interp->result.
1073 * If the last character of interp->result is a newline, then it
1074 * is removed. File errorId gets closed, and pidPtr is freed
1075 * back to the storage allocator.
1077 *----------------------------------------------------------------------
1080 static int JimCleanupChildren(Jim_Interp
*interp
, int numPids
, pidtype
*pidPtr
, fdtype errorId
)
1082 struct WaitInfoTable
*table
= Jim_CmdPrivData(interp
);
1083 int result
= JIM_OK
;
1086 for (i
= 0; i
< numPids
; i
++) {
1088 if (JimWaitForProcess(table
, pidPtr
[i
], &waitStatus
) != JIM_BAD_PID
) {
1089 if (JimCheckWaitStatus(interp
, pidPtr
[i
], waitStatus
) != JIM_OK
) {
1097 * Read the standard error file. If there's anything there,
1098 * then add the file's contents to the result
1101 if (errorId
!= JIM_BAD_FD
) {
1102 JimRewindFd(errorId
);
1103 if (JimAppendStreamToString(interp
, errorId
, Jim_GetResult(interp
)) != JIM_OK
) {
1108 Jim_RemoveTrailingNewline(Jim_GetResult(interp
));
1113 int Jim_execInit(Jim_Interp
*interp
)
1115 if (Jim_PackageProvide(interp
, "exec", "1.0", JIM_ERRMSG
))
1120 * Disable SIGPIPE signals: if they were allowed, this process
1121 * might go away unexpectedly if children misbehave. This code
1122 * can potentially interfere with other application code that
1123 * expects to handle SIGPIPEs.
1125 * By doing this in the init function, applications can override
1126 * this later. Note that child processes have SIGPIPE restored
1127 * to the default after vfork().
1129 (void)signal(SIGPIPE
, SIG_IGN
);
1132 Jim_CreateCommand(interp
, "exec", Jim_ExecCmd
, JimAllocWaitInfoTable(), JimFreeWaitInfoTable
);
1136 #if defined(__MINGW32__)
1137 /* Windows-specific (mingw) implementation */
1139 static SECURITY_ATTRIBUTES
*JimStdSecAttrs(void)
1141 static SECURITY_ATTRIBUTES secAtts
;
1143 secAtts
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
1144 secAtts
.lpSecurityDescriptor
= NULL
;
1145 secAtts
.bInheritHandle
= TRUE
;
1149 static int JimErrno(void)
1151 switch (GetLastError()) {
1152 case ERROR_FILE_NOT_FOUND
: return ENOENT
;
1153 case ERROR_PATH_NOT_FOUND
: return ENOENT
;
1154 case ERROR_TOO_MANY_OPEN_FILES
: return EMFILE
;
1155 case ERROR_ACCESS_DENIED
: return EACCES
;
1156 case ERROR_INVALID_HANDLE
: return EBADF
;
1157 case ERROR_BAD_ENVIRONMENT
: return E2BIG
;
1158 case ERROR_BAD_FORMAT
: return ENOEXEC
;
1159 case ERROR_INVALID_ACCESS
: return EACCES
;
1160 case ERROR_INVALID_DRIVE
: return ENOENT
;
1161 case ERROR_CURRENT_DIRECTORY
: return EACCES
;
1162 case ERROR_NOT_SAME_DEVICE
: return EXDEV
;
1163 case ERROR_NO_MORE_FILES
: return ENOENT
;
1164 case ERROR_WRITE_PROTECT
: return EROFS
;
1165 case ERROR_BAD_UNIT
: return ENXIO
;
1166 case ERROR_NOT_READY
: return EBUSY
;
1167 case ERROR_BAD_COMMAND
: return EIO
;
1168 case ERROR_CRC
: return EIO
;
1169 case ERROR_BAD_LENGTH
: return EIO
;
1170 case ERROR_SEEK
: return EIO
;
1171 case ERROR_WRITE_FAULT
: return EIO
;
1172 case ERROR_READ_FAULT
: return EIO
;
1173 case ERROR_GEN_FAILURE
: return EIO
;
1174 case ERROR_SHARING_VIOLATION
: return EACCES
;
1175 case ERROR_LOCK_VIOLATION
: return EACCES
;
1176 case ERROR_SHARING_BUFFER_EXCEEDED
: return ENFILE
;
1177 case ERROR_HANDLE_DISK_FULL
: return ENOSPC
;
1178 case ERROR_NOT_SUPPORTED
: return ENODEV
;
1179 case ERROR_REM_NOT_LIST
: return EBUSY
;
1180 case ERROR_DUP_NAME
: return EEXIST
;
1181 case ERROR_BAD_NETPATH
: return ENOENT
;
1182 case ERROR_NETWORK_BUSY
: return EBUSY
;
1183 case ERROR_DEV_NOT_EXIST
: return ENODEV
;
1184 case ERROR_TOO_MANY_CMDS
: return EAGAIN
;
1185 case ERROR_ADAP_HDW_ERR
: return EIO
;
1186 case ERROR_BAD_NET_RESP
: return EIO
;
1187 case ERROR_UNEXP_NET_ERR
: return EIO
;
1188 case ERROR_NETNAME_DELETED
: return ENOENT
;
1189 case ERROR_NETWORK_ACCESS_DENIED
: return EACCES
;
1190 case ERROR_BAD_DEV_TYPE
: return ENODEV
;
1191 case ERROR_BAD_NET_NAME
: return ENOENT
;
1192 case ERROR_TOO_MANY_NAMES
: return ENFILE
;
1193 case ERROR_TOO_MANY_SESS
: return EIO
;
1194 case ERROR_SHARING_PAUSED
: return EAGAIN
;
1195 case ERROR_REDIR_PAUSED
: return EAGAIN
;
1196 case ERROR_FILE_EXISTS
: return EEXIST
;
1197 case ERROR_CANNOT_MAKE
: return ENOSPC
;
1198 case ERROR_OUT_OF_STRUCTURES
: return ENFILE
;
1199 case ERROR_ALREADY_ASSIGNED
: return EEXIST
;
1200 case ERROR_INVALID_PASSWORD
: return EPERM
;
1201 case ERROR_NET_WRITE_FAULT
: return EIO
;
1202 case ERROR_NO_PROC_SLOTS
: return EAGAIN
;
1203 case ERROR_DISK_CHANGE
: return EXDEV
;
1204 case ERROR_BROKEN_PIPE
: return EPIPE
;
1205 case ERROR_OPEN_FAILED
: return ENOENT
;
1206 case ERROR_DISK_FULL
: return ENOSPC
;
1207 case ERROR_NO_MORE_SEARCH_HANDLES
: return EMFILE
;
1208 case ERROR_INVALID_TARGET_HANDLE
: return EBADF
;
1209 case ERROR_INVALID_NAME
: return ENOENT
;
1210 case ERROR_PROC_NOT_FOUND
: return ESRCH
;
1211 case ERROR_WAIT_NO_CHILDREN
: return ECHILD
;
1212 case ERROR_CHILD_NOT_COMPLETE
: return ECHILD
;
1213 case ERROR_DIRECT_ACCESS_HANDLE
: return EBADF
;
1214 case ERROR_SEEK_ON_DEVICE
: return ESPIPE
;
1215 case ERROR_BUSY_DRIVE
: return EAGAIN
;
1216 case ERROR_DIR_NOT_EMPTY
: return EEXIST
;
1217 case ERROR_NOT_LOCKED
: return EACCES
;
1218 case ERROR_BAD_PATHNAME
: return ENOENT
;
1219 case ERROR_LOCK_FAILED
: return EACCES
;
1220 case ERROR_ALREADY_EXISTS
: return EEXIST
;
1221 case ERROR_FILENAME_EXCED_RANGE
: return ENAMETOOLONG
;
1222 case ERROR_BAD_PIPE
: return EPIPE
;
1223 case ERROR_PIPE_BUSY
: return EAGAIN
;
1224 case ERROR_PIPE_NOT_CONNECTED
: return EPIPE
;
1225 case ERROR_DIRECTORY
: return ENOTDIR
;
1230 static int JimPipe(fdtype pipefd
[2])
1232 if (CreatePipe(&pipefd
[0], &pipefd
[1], NULL
, 0)) {
1238 static fdtype
JimDupFd(fdtype infd
)
1241 pidtype pid
= GetCurrentProcess();
1243 if (DuplicateHandle(pid
, infd
, pid
, &dupfd
, 0, TRUE
, DUPLICATE_SAME_ACCESS
)) {
1249 static int JimRewindFd(fdtype fd
)
1251 return SetFilePointer(fd
, 0, NULL
, FILE_BEGIN
) == INVALID_SET_FILE_POINTER
? -1 : 0;
1255 static int JimReadFd(fdtype fd
, char *buffer
, size_t len
)
1259 if (ReadFile(fd
, buffer
, len
, &num
, NULL
)) {
1262 if (GetLastError() == ERROR_HANDLE_EOF
|| GetLastError() == ERROR_BROKEN_PIPE
) {
1269 static FILE *JimFdOpenForRead(fdtype fd
)
1271 return _fdopen(_open_osfhandle((int)fd
, _O_RDONLY
| _O_TEXT
), "r");
1274 static fdtype
JimFileno(FILE *fh
)
1276 return (fdtype
)_get_osfhandle(_fileno(fh
));
1279 static fdtype
JimOpenForRead(const char *filename
)
1281 return CreateFile(filename
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1282 JimStdSecAttrs(), OPEN_EXISTING
, 0, NULL
);
1285 static fdtype
JimOpenForWrite(const char *filename
, int append
)
1287 return CreateFile(filename
, append
? FILE_APPEND_DATA
: GENERIC_WRITE
, FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1288 JimStdSecAttrs(), append
? OPEN_ALWAYS
: CREATE_ALWAYS
, 0, (HANDLE
) NULL
);
1291 static FILE *JimFdOpenForWrite(fdtype fd
)
1293 return _fdopen(_open_osfhandle((int)fd
, _O_TEXT
), "w");
1296 static pidtype
JimWaitPid(pidtype pid
, int *status
, int nohang
)
1298 DWORD ret
= WaitForSingleObject(pid
, nohang
? 0 : INFINITE
);
1299 if (ret
== WAIT_TIMEOUT
|| ret
== WAIT_FAILED
) {
1300 /* WAIT_TIMEOUT can only happend with WNOHANG */
1303 GetExitCodeProcess(pid
, &ret
);
1309 static HANDLE
JimCreateTemp(Jim_Interp
*interp
, const char *contents
, int len
)
1311 char name
[MAX_PATH
];
1314 if (!GetTempPath(MAX_PATH
, name
) || !GetTempFileName(name
, "JIM", 0, name
)) {
1318 handle
= CreateFile(name
, GENERIC_READ
| GENERIC_WRITE
, 0, JimStdSecAttrs(),
1319 CREATE_ALWAYS
, FILE_ATTRIBUTE_TEMPORARY
| FILE_FLAG_DELETE_ON_CLOSE
,
1322 if (handle
== INVALID_HANDLE_VALUE
) {
1326 if (contents
!= NULL
) {
1327 /* Use fdopen() to get automatic text-mode translation */
1328 FILE *fh
= JimFdOpenForWrite(JimDupFd(handle
));
1333 if (fwrite(contents
, len
, 1, fh
) != 1) {
1337 fseek(fh
, 0, SEEK_SET
);
1343 Jim_SetResultErrno(interp
, "failed to create temp file");
1344 CloseHandle(handle
);
1350 JimWinFindExecutable(const char *originalName
, char fullPath
[MAX_PATH
])
1353 static char extensions
[][5] = {".exe", "", ".bat"};
1355 for (i
= 0; i
< (int) (sizeof(extensions
) / sizeof(extensions
[0])); i
++) {
1356 lstrcpyn(fullPath
, originalName
, MAX_PATH
- 5);
1357 lstrcat(fullPath
, extensions
[i
]);
1359 if (SearchPath(NULL
, fullPath
, NULL
, MAX_PATH
, fullPath
, NULL
) == 0) {
1362 if (GetFileAttributes(fullPath
) & FILE_ATTRIBUTE_DIRECTORY
) {
1371 static char **JimSaveEnv(char **env
)
1376 static void JimRestoreEnv(char **env
)
1378 JimFreeEnv(env
, Jim_GetEnviron());
1382 JimWinBuildCommandLine(Jim_Interp
*interp
, char **argv
)
1384 char *start
, *special
;
1387 Jim_Obj
*strObj
= Jim_NewStringObj(interp
, "", 0);
1389 for (i
= 0; argv
[i
]; i
++) {
1391 Jim_AppendString(interp
, strObj
, " ", 1);
1394 if (argv
[i
][0] == '\0') {
1399 for (start
= argv
[i
]; *start
!= '\0'; start
++) {
1400 if (isspace(UCHAR(*start
))) {
1407 Jim_AppendString(interp
, strObj
, "\"" , 1);
1411 for (special
= argv
[i
]; ; ) {
1412 if ((*special
== '\\') && (special
[1] == '\\' ||
1413 special
[1] == '"' || (quote
&& special
[1] == '\0'))) {
1414 Jim_AppendString(interp
, strObj
, start
, special
- start
);
1418 if (*special
== '"' || (quote
&& *special
== '\0')) {
1420 * N backslashes followed a quote -> insert
1421 * N * 2 + 1 backslashes then a quote.
1424 Jim_AppendString(interp
, strObj
, start
, special
- start
);
1427 if (*special
!= '\\') {
1431 Jim_AppendString(interp
, strObj
, start
, special
- start
);
1434 if (*special
== '"') {
1435 if (special
== start
) {
1436 Jim_AppendString(interp
, strObj
, "\"", 1);
1439 Jim_AppendString(interp
, strObj
, start
, special
- start
);
1441 Jim_AppendString(interp
, strObj
, "\\\"", 2);
1442 start
= special
+ 1;
1444 if (*special
== '\0') {
1449 Jim_AppendString(interp
, strObj
, start
, special
- start
);
1451 Jim_AppendString(interp
, strObj
, "\"", 1);
1458 JimStartWinProcess(Jim_Interp
*interp
, char **argv
, char *env
, fdtype inputId
, fdtype outputId
, fdtype errorId
)
1460 STARTUPINFO startInfo
;
1461 PROCESS_INFORMATION procInfo
;
1463 char execPath
[MAX_PATH
];
1464 pidtype pid
= JIM_BAD_PID
;
1465 Jim_Obj
*cmdLineObj
;
1467 if (JimWinFindExecutable(argv
[0], execPath
) < 0) {
1472 hProcess
= GetCurrentProcess();
1473 cmdLineObj
= JimWinBuildCommandLine(interp
, argv
);
1476 * STARTF_USESTDHANDLES must be used to pass handles to child process.
1477 * Using SetStdHandle() and/or dup2() only works when a console mode
1478 * parent process is spawning an attached console mode child process.
1481 ZeroMemory(&startInfo
, sizeof(startInfo
));
1482 startInfo
.cb
= sizeof(startInfo
);
1483 startInfo
.dwFlags
= STARTF_USESTDHANDLES
;
1484 startInfo
.hStdInput
= INVALID_HANDLE_VALUE
;
1485 startInfo
.hStdOutput
= INVALID_HANDLE_VALUE
;
1486 startInfo
.hStdError
= INVALID_HANDLE_VALUE
;
1489 * Duplicate all the handles which will be passed off as stdin, stdout
1490 * and stderr of the child process. The duplicate handles are set to
1491 * be inheritable, so the child process can use them.
1493 if (inputId
== JIM_BAD_FD
) {
1494 if (CreatePipe(&startInfo
.hStdInput
, &h
, JimStdSecAttrs(), 0) != FALSE
) {
1498 DuplicateHandle(hProcess
, inputId
, hProcess
, &startInfo
.hStdInput
,
1499 0, TRUE
, DUPLICATE_SAME_ACCESS
);
1501 if (startInfo
.hStdInput
== JIM_BAD_FD
) {
1505 if (outputId
== JIM_BAD_FD
) {
1506 startInfo
.hStdOutput
= CreateFile("NUL:", GENERIC_WRITE
, 0,
1507 JimStdSecAttrs(), OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
1509 DuplicateHandle(hProcess
, outputId
, hProcess
, &startInfo
.hStdOutput
,
1510 0, TRUE
, DUPLICATE_SAME_ACCESS
);
1512 if (startInfo
.hStdOutput
== JIM_BAD_FD
) {
1516 if (errorId
== JIM_BAD_FD
) {
1518 * If handle was not set, errors should be sent to an infinitely
1522 startInfo
.hStdError
= CreateFile("NUL:", GENERIC_WRITE
, 0,
1523 JimStdSecAttrs(), OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
1525 DuplicateHandle(hProcess
, errorId
, hProcess
, &startInfo
.hStdError
,
1526 0, TRUE
, DUPLICATE_SAME_ACCESS
);
1528 if (startInfo
.hStdError
== JIM_BAD_FD
) {
1532 if (!CreateProcess(NULL
, (char *)Jim_String(cmdLineObj
), NULL
, NULL
, TRUE
,
1533 0, env
, NULL
, &startInfo
, &procInfo
)) {
1538 * "When an application spawns a process repeatedly, a new thread
1539 * instance will be created for each process but the previous
1540 * instances may not be cleaned up. This results in a significant
1541 * virtual memory loss each time the process is spawned. If there
1542 * is a WaitForInputIdle() call between CreateProcess() and
1543 * CloseHandle(), the problem does not occur." PSS ID Number: Q124121
1546 WaitForInputIdle(procInfo
.hProcess
, 5000);
1547 CloseHandle(procInfo
.hThread
);
1549 pid
= procInfo
.hProcess
;
1552 Jim_FreeNewObj(interp
, cmdLineObj
);
1553 if (startInfo
.hStdInput
!= JIM_BAD_FD
) {
1554 CloseHandle(startInfo
.hStdInput
);
1556 if (startInfo
.hStdOutput
!= JIM_BAD_FD
) {
1557 CloseHandle(startInfo
.hStdOutput
);
1559 if (startInfo
.hStdError
!= JIM_BAD_FD
) {
1560 CloseHandle(startInfo
.hStdError
);
1565 /* Unix-specific implementation */
1566 static int JimOpenForWrite(const char *filename
, int append
)
1568 return open(filename
, O_WRONLY
| O_CREAT
| (append
? O_APPEND
: O_TRUNC
), 0666);
1571 static int JimRewindFd(int fd
)
1573 return lseek(fd
, 0L, SEEK_SET
);
1576 static int JimCreateTemp(Jim_Interp
*interp
, const char *contents
, int len
)
1578 char inName
[] = "/tmp/tcl.tmp.XXXXXX";
1580 int fd
= mkstemp(inName
);
1581 if (fd
== JIM_BAD_FD
) {
1582 Jim_SetResultErrno(interp
, "couldn't create temp file");
1587 if (write(fd
, contents
, len
) != len
) {
1588 Jim_SetResultErrno(interp
, "couldn't write temp file");
1592 lseek(fd
, 0L, SEEK_SET
);
1597 static char **JimSaveEnv(char **env
)
1599 char **saveenv
= Jim_GetEnviron();
1600 Jim_SetEnviron(env
);
1604 static void JimRestoreEnv(char **env
)
1606 JimFreeEnv(Jim_GetEnviron(), env
);
1607 Jim_SetEnviron(env
);