1 /* Concurrent shell support for the Midnight Commander
2 Copyright (C) 1994, 1995, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3 2005, 2006, 2007 Free Software Foundation, Inc.
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of Version 2 of the GNU General Public
7 License, as published by the Free Software Foundation.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * \brief Source: concurrent shell support
25 #ifdef HAVE_SUBSHELL_SUPPORT
28 # define _GNU_SOURCE 1
38 #include <sys/types.h>
40 #ifdef HAVE_SYS_IOCTL_H
41 # include <sys/ioctl.h>
47 # include <stropts.h> /* For I_PUSH */
48 #endif /* HAVE_STROPTS_H */
50 #include "lib/global.h"
51 #include "lib/tty/tty.h" /* LINES */
52 #include "lib/tty/key.h" /* XCTRL */
53 #include "lib/vfs/mc-vfs/vfs.h"
54 #include "lib/strutil.h"
55 #include "lib/fileloc.h"
57 #include "panel.h" /* current_panel */
58 #include "wtools.h" /* query_dialog() */
59 #include "main.h" /* do_update_prompt() */
60 #include "consaver/cons.saver.h" /* handle_console() */
64 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
68 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
71 /* tcsh closes all non-standard file descriptors, so we have to use a pipe */
72 static char tcsh_fifo
[128];
75 static void init_raw_mode (void);
76 static gboolean
feed_subshell (int how
, int fail_on_error
);
77 static void synchronize (void);
78 static int pty_open_master (char *pty_name
);
79 static int pty_open_slave (const char *pty_name
);
80 static int resize_tty (int fd
);
83 # define STDIN_FILENO 0
87 # define STDOUT_FILENO 1
91 # define STDERR_FILENO 2
94 /* If using a subshell for evaluating commands this is true */
96 #ifdef SUBSHELL_OPTIONAL
102 /* File descriptors of the pseudoterminal used by the subshell */
103 int subshell_pty
= 0;
104 static int subshell_pty_slave
= -1;
106 /* The key for switching back to MC from the subshell */
107 static const char subshell_switch_key
= XCTRL ('o') & 255;
109 /* State of the subshell:
110 * INACTIVE: the default state; awaiting a command
111 * ACTIVE: remain in the shell until the user hits `subshell_switch_key'
112 * RUNNING_COMMAND: return to MC when the current command finishes */
113 enum subshell_state_enum
116 /* Holds the latest prompt captured from the subshell */
118 subshell_prompt
= NULL
;
120 /* Initial length of the buffer for the subshell's prompt */
121 #define INITIAL_PROMPT_SIZE 10
123 /* Used by the child process to indicate failure to start the subshell */
124 #define FORK_FAILURE 69 /* Arbitrary */
126 /* Length of the buffer for all I/O with the subshell */
127 #define PTY_BUFFER_SIZE BUF_SMALL /* Arbitrary; but keep it >= 80 */
132 READ
= 0, WRITE
= 1 };
135 pty_buffer
[PTY_BUFFER_SIZE
] = "\0"; /* For reading/writing on the subshell's pty */
137 subshell_pipe
[2]; /* To pass CWD info from the subshell to MC */
139 subshell_pid
= 1; /* The subshell's process ID */
141 subshell_cwd
[MC_MAXPATHLEN
+ 1]; /* One extra char for final '\n' */
143 /* Subshell type (gleaned from the SHELL environment variable, if available) */
152 /* Flag to indicate whether the subshell is ready for next command */
156 /* The following two flags can be changed by the SIGCHLD handler. This is */
157 /* OK, because the `int' type is updated atomically on all known machines */
162 /* We store the terminal's initial mode here so that we can configure
163 the pty similarly, and also so we can restore the real terminal to
164 sanity if we have to exit abruptly */
165 static struct termios
168 /* This is a transparent mode for the terminal where MC is running on */
169 /* It is used when the shell is active, so that the control signals */
170 /* are delivered to the shell pty */
171 static struct termios
174 /* This counter indicates how many characters of prompt we have read */
175 /* FIXME: try to figure out why this had to become global */
181 * Write all data, even if the write() call is interrupted.
185 write_all (int fd
, const void *buf
, size_t count
)
191 ret
= write (fd
, (const unsigned char *) buf
+ written
, count
);
200 return written
> 0 ? written
: ret
;
210 * Prepare child process to running the shell and run it.
212 * Modifies the global variables (in the child process only):
218 init_subshell_child (const char *pty_name
)
220 const char *init_file
= NULL
;
224 setsid (); /* Get a fresh terminal session */
226 /* Make sure that it has become our controlling terminal */
228 /* Redundant on Linux and probably most systems, but just in case: */
231 ioctl (subshell_pty_slave
, TIOCSCTTY
, 0);
234 /* Configure its terminal modes and window size */
236 /* Set up the pty with the same termios flags as our own tty */
237 if (tcsetattr (subshell_pty_slave
, TCSANOW
, &shell_mode
))
239 fprintf (stderr
, "Cannot set pty terminal modes: %s\r\n", unix_error_string (errno
));
240 _exit (FORK_FAILURE
);
243 /* Set the pty's size (80x25 by default on Linux) according to the */
244 /* size of the real terminal as calculated by ncurses, if possible */
245 resize_tty (subshell_pty_slave
);
247 /* Set up the subshell's environment and init file name */
249 /* It simplifies things to change to our home directory here, */
250 /* and the user's startup file may do a `cd' command anyway */
253 ret
= chdir (home_dir
); /* FIXME? What about when we re-run the subshell? */
256 /* Set MC_SID to prevent running one mc from another */
260 char sid_str
[BUF_SMALL
];
261 g_snprintf (sid_str
, sizeof (sid_str
), "MC_SID=%ld", (long) mc_sid
);
262 putenv (g_strdup (sid_str
));
265 switch (subshell_type
)
268 init_file
= MC_USERCONF_DIR PATH_SEP_STR
"bashrc";
269 if (access (init_file
, R_OK
) == -1)
270 init_file
= ".bashrc";
272 /* Make MC's special commands not show up in bash's history */
273 putenv ((char *) "HISTCONTROL=ignorespace");
275 /* Allow alternative readline settings for MC */
276 if (access (MC_USERCONF_DIR PATH_SEP_STR
"inputrc", R_OK
) == 0)
277 putenv ((char *) "INPUTRC=" MC_USERCONF_DIR PATH_SEP_STR
"/inputrc");
281 /* TODO: Find a way to pass initfile to TCSH and ZSH */
288 fprintf (stderr
, __FILE__
": unimplemented subshell type %d\r\n", subshell_type
);
289 _exit (FORK_FAILURE
);
292 /* Attach all our standard file descriptors to the pty */
294 /* This is done just before the fork, because stderr must still */
295 /* be connected to the real tty during the above error messages; */
296 /* otherwise the user will never see them. */
298 dup2 (subshell_pty_slave
, STDIN_FILENO
);
299 dup2 (subshell_pty_slave
, STDOUT_FILENO
);
300 dup2 (subshell_pty_slave
, STDERR_FILENO
);
302 close (subshell_pipe
[READ
]);
303 close (subshell_pty_slave
); /* These may be FD_CLOEXEC, but just in case... */
304 /* Close master side of pty. This is important; apart from */
305 /* freeing up the descriptor for use in the subshell, it also */
306 /* means that when MC exits, the subshell will get a SIGHUP and */
307 /* exit too, because there will be no more descriptors pointing */
308 /* at the master side of the pty and so it will disappear. */
309 close (subshell_pty
);
311 /* Execute the subshell at last */
313 switch (subshell_type
)
316 execl (shell
, "bash", "-rcfile", init_file
, (char *) NULL
);
320 execl (shell
, "tcsh", (char *) NULL
);
324 /* Use -g to exclude cmds beginning with space from history
325 * and -Z to use the line editor on non-interactive term */
326 execl (shell
, "zsh", "-Z", "-g", (char *) NULL
);
331 execl (shell
, "fish", (char *) NULL
);
335 /* If we get this far, everything failed miserably */
336 _exit (FORK_FAILURE
);
341 * Check MC_SID to prevent running one mc from another.
343 * 0 if no parent mc in our session was found,
344 * 1 if parent mc was found and the user wants to continue,
345 * 2 if parent mc was found and the user wants to quit mc.
350 pid_t my_sid
, old_sid
;
354 sid_str
= getenv ("MC_SID");
358 old_sid
= (pid_t
) strtol (sid_str
, NULL
, 0);
366 /* The parent mc is in a different session, it's OK */
367 if (old_sid
!= my_sid
)
370 r
= query_dialog (_("Warning"),
371 _("GNU Midnight Commander is already\n"
372 "running on this terminal.\n"
373 "Subshell support will be disabled."), D_ERROR
, 2, _("&OK"), _("&Quit"));
384 * Fork the subshell, and set up many, many things.
386 * Possibly modifies the global variables:
387 * subshell_type, subshell_alive, subshell_stopped, subshell_pid
388 * use_subshell - Is set to FALSE if we can't run the subshell
389 * quit - Can be set to SUBSHELL_EXIT by the SIGCHLD handler
395 /* This must be remembered across calls to init_subshell() */
396 static char pty_name
[BUF_SMALL
];
397 char precmd
[BUF_SMALL
];
399 switch (check_sid ())
402 use_subshell
= FALSE
;
405 use_subshell
= FALSE
;
406 midnight_shutdown
= 1;
410 /* Take the current (hopefully pristine) tty mode and make */
411 /* a raw mode based on it now, before we do anything else with it */
414 if (subshell_pty
== 0)
415 { /* First time through */
416 /* Find out what type of shell we have */
418 if (strstr (shell
, "/zsh") || getenv ("ZSH_VERSION"))
420 else if (strstr (shell
, "/tcsh"))
421 subshell_type
= TCSH
;
422 else if (strstr (shell
, "/csh"))
423 subshell_type
= TCSH
;
424 else if (strstr (shell
, "/bash") || getenv ("BASH"))
425 subshell_type
= BASH
;
426 else if (strstr (shell
, "/fish"))
427 subshell_type
= FISH
;
430 use_subshell
= FALSE
;
434 /* Open a pty for talking to the subshell */
436 /* FIXME: We may need to open a fresh pty each time on SVR4 */
438 subshell_pty
= pty_open_master (pty_name
);
439 if (subshell_pty
== -1)
441 fprintf (stderr
, "Cannot open master side of pty: %s\r\n", unix_error_string (errno
));
442 use_subshell
= FALSE
;
445 subshell_pty_slave
= pty_open_slave (pty_name
);
446 if (subshell_pty_slave
== -1)
448 fprintf (stderr
, "Cannot open slave side of pty %s: %s\r\n",
449 pty_name
, unix_error_string (errno
));
450 use_subshell
= FALSE
;
454 /* Create a pipe for receiving the subshell's CWD */
456 if (subshell_type
== TCSH
)
458 g_snprintf (tcsh_fifo
, sizeof (tcsh_fifo
), "%s/mc.pipe.%d",
459 mc_tmpdir (), (int) getpid ());
460 if (mkfifo (tcsh_fifo
, 0600) == -1)
462 fprintf (stderr
, "mkfifo(%s) failed: %s\r\n", tcsh_fifo
, unix_error_string (errno
));
463 use_subshell
= FALSE
;
467 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
469 if ((subshell_pipe
[READ
] = open (tcsh_fifo
, O_RDWR
)) == -1
470 || (subshell_pipe
[WRITE
] = open (tcsh_fifo
, O_RDWR
)) == -1)
472 fprintf (stderr
, _("Cannot open named pipe %s\n"), tcsh_fifo
);
473 perror (__FILE__
": open");
474 use_subshell
= FALSE
;
478 else /* subshell_type is BASH or ZSH */ if (pipe (subshell_pipe
))
480 perror (__FILE__
": couldn't create pipe");
481 use_subshell
= FALSE
;
486 /* Fork the subshell */
488 subshell_alive
= TRUE
;
489 subshell_stopped
= FALSE
;
490 subshell_pid
= fork ();
492 if (subshell_pid
== -1)
494 fprintf (stderr
, "Cannot spawn the subshell process: %s\r\n", unix_error_string (errno
));
495 /* We exit here because, if the process table is full, the */
496 /* other method of running user commands won't work either */
500 if (subshell_pid
== 0)
502 /* We are in the child process */
503 init_subshell_child (pty_name
);
506 /* Set up `precmd' or equivalent for reading the subshell's CWD */
508 switch (subshell_type
)
511 g_snprintf (precmd
, sizeof (precmd
),
512 " PROMPT_COMMAND='pwd>&%d;kill -STOP $$'\n", subshell_pipe
[WRITE
]);
516 g_snprintf (precmd
, sizeof (precmd
),
517 " precmd(){ pwd>&%d;kill -STOP $$ }\n", subshell_pipe
[WRITE
]);
521 g_snprintf (precmd
, sizeof (precmd
),
522 "set echo_style=both;"
523 "alias precmd 'echo $cwd:q >>%s;kill -STOP $$'\n", tcsh_fifo
);
526 g_snprintf (precmd
, sizeof (precmd
),
527 "function fish_prompt ; pwd>&%d;kill -STOP %%self; end\n",
528 subshell_pipe
[WRITE
]);
532 write_all (subshell_pty
, precmd
, strlen (precmd
));
534 /* Wait until the subshell has started up and processed the command */
536 subshell_state
= RUNNING_COMMAND
;
537 tty_enable_interrupt_key ();
538 if (!feed_subshell (QUIETLY
, TRUE
))
540 use_subshell
= FALSE
;
542 tty_disable_interrupt_key ();
544 use_subshell
= FALSE
; /* Subshell died instantly, so don't use it */
551 static int initialized
= 0;
553 /* MC calls tty_reset_shell_mode() in pre_exec() to set the real tty to its */
554 /* original settings. However, here we need to make this tty very raw, */
555 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
556 /* pty. So, instead of changing the code for execute(), pre_exec(), */
557 /* etc, we just set up the modes we need here, before each command. */
559 if (initialized
== 0) /* First time: initialise `raw_mode' */
561 tcgetattr (STDOUT_FILENO
, &raw_mode
);
562 raw_mode
.c_lflag
&= ~ICANON
; /* Disable line-editing chars, etc. */
563 raw_mode
.c_lflag
&= ~ISIG
; /* Disable intr, quit & suspend chars */
564 raw_mode
.c_lflag
&= ~ECHO
; /* Disable input echoing */
565 raw_mode
.c_iflag
&= ~IXON
; /* Pass ^S/^Q to subshell undisturbed */
566 raw_mode
.c_iflag
&= ~ICRNL
; /* Don't translate CRs into LFs */
567 raw_mode
.c_oflag
&= ~OPOST
; /* Don't postprocess output */
568 raw_mode
.c_cc
[VTIME
] = 0; /* IE: wait forever, and return as */
569 raw_mode
.c_cc
[VMIN
] = 1; /* soon as a character is available */
576 invoke_subshell (const char *command
, int how
, char **new_dir
)
580 /* Make the MC terminal transparent */
581 tcsetattr (STDOUT_FILENO
, TCSANOW
, &raw_mode
);
583 /* Make the subshell change to MC's working directory */
585 do_subshell_chdir (current_panel
->cwd
, TRUE
, 1);
587 if (command
== NULL
) /* The user has done "C-o" from MC */
589 if (subshell_state
== INACTIVE
)
591 subshell_state
= ACTIVE
;
592 /* FIXME: possibly take out this hack; the user can
593 re-play it by hitting C-hyphen a few times! */
595 write_all (subshell_pty
, " \b", 2); /* Hack to make prompt reappear */
598 else /* MC has passed us a user command */
601 write_all (subshell_pty
, " ", 1);
602 /* FIXME: if command is long (>8KB ?) we go comma */
603 write_all (subshell_pty
, command
, strlen (command
));
604 write_all (subshell_pty
, "\n", 1);
605 subshell_state
= RUNNING_COMMAND
;
606 subshell_ready
= FALSE
;
609 feed_subshell (how
, FALSE
);
611 pcwd
= vfs_translate_path_n (current_panel
->cwd
);
612 if (new_dir
&& subshell_alive
&& strcmp (subshell_cwd
, pcwd
))
613 *new_dir
= subshell_cwd
; /* Make MC change to the subshell's CWD */
616 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
617 while (!subshell_alive
&& !quit
&& use_subshell
)
627 read_subshell_prompt (void)
629 static int prompt_size
= INITIAL_PROMPT_SIZE
;
630 int bytes
= 0, i
, rc
= 0;
631 struct timeval timeleft
= { 0, 0 };
635 FD_SET (subshell_pty
, &tmp
);
637 if (subshell_prompt
== NULL
)
638 { /* First time through */
639 subshell_prompt
= g_malloc (prompt_size
);
640 *subshell_prompt
= '\0';
644 while (subshell_alive
&& (rc
= select (subshell_pty
+ 1, &tmp
, NULL
, NULL
, &timeleft
)))
646 /* Check for `select' errors */
653 fprintf (stderr
, "select (FD_SETSIZE, &tmp...): %s\r\n", unix_error_string (errno
));
658 bytes
= read (subshell_pty
, pty_buffer
, sizeof (pty_buffer
));
660 /* Extract the prompt from the shell output */
662 for (i
= 0; i
< bytes
; ++i
)
663 if (pty_buffer
[i
] == '\n' || pty_buffer
[i
] == '\r')
672 subshell_prompt
[prompt_pos
++] = pty_buffer
[i
];
673 if (prompt_pos
== prompt_size
)
674 subshell_prompt
= g_realloc (subshell_prompt
, prompt_size
*= 2);
677 subshell_prompt
[prompt_pos
] = '\0';
679 if (rc
== 0 && bytes
== 0)
684 /* Resize given terminal using TIOCSWINSZ, return ioctl() result */
688 #if defined TIOCSWINSZ
689 struct winsize tty_size
;
691 tty_size
.ws_row
= LINES
;
692 tty_size
.ws_col
= COLS
;
693 tty_size
.ws_xpixel
= tty_size
.ws_ypixel
= 0;
695 return ioctl (fd
, TIOCSWINSZ
, &tty_size
);
701 /* Resize subshell_pty */
703 resize_subshell (void)
705 if (use_subshell
== 0)
708 resize_tty (subshell_pty
);
714 int subshell_quit
= TRUE
;
716 if (subshell_state
!= INACTIVE
&& subshell_alive
)
718 !query_dialog (_("Warning"),
719 _(" The shell is still active. Quit anyway? "),
720 D_NORMAL
, 2, _("&Yes"), _("&No"));
724 if (subshell_type
== TCSH
)
726 if (unlink (tcsh_fifo
) == -1)
727 fprintf (stderr
, "Cannot remove named pipe %s: %s\r\n",
728 tcsh_fifo
, unix_error_string (errno
));
731 g_free (subshell_prompt
);
732 subshell_prompt
= NULL
;
733 pty_buffer
[0] = '\0';
736 return subshell_quit
;
741 * Carefully quote directory name to allow entering any directory safely,
742 * no matter what weird characters it may contain in its name.
743 * NOTE: Treat directory name an untrusted data, don't allow it to cause
744 * executing any commands in the shell. Escape all control characters.
745 * Use following technique:
747 * printf(1) with format string containing a single conversion specifier,
748 * "b", and an argument which contains a copy of the string passed to
749 * subshell_name_quote() with all characters, except digits and letters,
750 * replaced by the backslash-escape sequence \0nnn, where "nnn" is the
751 * numeric value of the character converted to octal number.
753 * cd "`printf "%b" 'ABC\0nnnDEF\0nnnXYZ'`"
757 subshell_name_quote (const char *s
)
761 const char *quote_cmd_start
, *quote_cmd_end
;
764 if (subshell_type
== FISH
)
766 quote_cmd_start
= "(printf \"%b\" '";
767 quote_cmd_end
= "')";
771 quote_cmd_start
= "\"`printf \"%b\" '";
772 quote_cmd_end
= "'`\"";
775 /* Factor 5 because we need \, 0 and 3 other digits per character. */
776 d
= ret
= g_try_malloc (1 + (5 * strlen (s
)) + (strlen (quote_cmd_start
))
777 + (strlen (quote_cmd_end
)));
781 /* Prevent interpreting leading `-' as a switch for `cd' */
788 /* Copy the beginning of the command to the buffer */
789 strcpy (d
, quote_cmd_start
);
790 d
+= strlen (quote_cmd_start
);
793 * Print every character except digits and letters as a backslash-escape
794 * sequence of the form \0nnn, where "nnn" is the numeric value of the
795 * character converted to octal number.
798 for (; su
[0] != '\0';)
800 n
= str_cget_next_char_safe (su
);
801 if (str_isalnum (su
))
803 memcpy (d
, su
, n
- su
);
808 for (c
= 0; c
< n
- su
; c
++)
810 sprintf (d
, "\\0%03o", (unsigned char) su
[c
]);
817 strcpy (d
, quote_cmd_end
);
823 /* If it actually changed the directory it returns true */
825 do_subshell_chdir (const char *directory
, int do_update
, int reset_prompt
)
831 pcwd
= vfs_translate_path_n (current_panel
->cwd
);
833 if (!(subshell_state
== INACTIVE
&& strcmp (subshell_cwd
, pcwd
)))
835 /* We have to repaint the subshell prompt if we read it from
836 * the main program. Please note that in the code after this
837 * if, the cd command that is sent will make the subshell
838 * repaint the prompt, so we don't have to paint it. */
845 /* The initial space keeps this out of the command history (in bash
846 because we set "HISTCONTROL=ignorespace") */
847 write_all (subshell_pty
, " cd ", 4);
850 translate
= vfs_translate_path_n (directory
);
853 temp
= subshell_name_quote (translate
);
856 write_all (subshell_pty
, temp
, strlen (temp
));
861 /* Should not happen unless the directory name is so long
862 that we don't have memory to quote it. */
863 write_all (subshell_pty
, ".", 1);
869 write_all (subshell_pty
, ".", 1);
874 write_all (subshell_pty
, "/", 1);
876 write_all (subshell_pty
, "\n", 1);
878 subshell_state
= RUNNING_COMMAND
;
879 feed_subshell (QUIETLY
, FALSE
);
883 int bPathNotEq
= strcmp (subshell_cwd
, pcwd
);
885 if (bPathNotEq
&& subshell_type
== TCSH
)
887 char rp_subshell_cwd
[PATH_MAX
];
888 char rp_current_panel_cwd
[PATH_MAX
];
890 char *p_subshell_cwd
= mc_realpath (subshell_cwd
, rp_subshell_cwd
);
891 char *p_current_panel_cwd
= mc_realpath (pcwd
, rp_current_panel_cwd
);
893 if (p_subshell_cwd
== NULL
)
894 p_subshell_cwd
= subshell_cwd
;
895 if (p_current_panel_cwd
== NULL
)
896 p_current_panel_cwd
= pcwd
;
897 bPathNotEq
= strcmp (p_subshell_cwd
, p_current_panel_cwd
);
900 if (bPathNotEq
&& strcmp (pcwd
, "."))
902 char *cwd
= strip_password (g_strdup (pcwd
), 1);
903 fprintf (stderr
, _("Warning: Cannot change to %s.\n"), cwd
);
910 update_prompt
= FALSE
;
913 /* Make sure that MC never stores the CWD in a silly format */
914 /* like /usr////lib/../bin, or the strcmp() above will fail */
919 subshell_get_console_attributes (void)
921 /* Get our current terminal modes */
923 if (tcgetattr (STDOUT_FILENO
, &shell_mode
))
925 fprintf (stderr
, "Cannot get terminal settings: %s\r\n", unix_error_string (errno
));
926 use_subshell
= FALSE
;
932 /* Figure out whether the subshell has stopped, exited or been killed */
933 /* Possibly modifies: `subshell_alive', `subshell_stopped' and `quit' */
935 sigchld_handler (int sig
)
942 pid
= waitpid (subshell_pid
, &status
, WUNTRACED
| WNOHANG
);
944 if (pid
== subshell_pid
)
946 /* Figure out what has happened to the subshell */
948 if (WIFSTOPPED (status
))
950 if (WSTOPSIG (status
) == SIGSTOP
)
952 /* The subshell has received a SIGSTOP signal */
953 subshell_stopped
= TRUE
;
957 /* The user has suspended the subshell. Revive it */
958 kill (subshell_pid
, SIGCONT
);
963 /* The subshell has either exited normally or been killed */
964 subshell_alive
= FALSE
;
965 delete_select_channel (subshell_pty
);
966 if (WIFEXITED (status
) && WEXITSTATUS (status
) != FORK_FAILURE
)
967 quit
|= SUBSHELL_EXIT
; /* Exited normally */
971 pid
= waitpid (cons_saver_pid
, &status
, WUNTRACED
| WNOHANG
);
973 if (pid
== cons_saver_pid
)
976 if (WIFSTOPPED (status
))
977 /* Someone has stopped cons.saver - restart it */
981 /* cons.saver has died - disable confole saving */
982 handle_console (CONSOLE_DONE
);
987 #endif /* __linux__ */
989 /* If we got here, some other child exited; ignore it */
993 /* Feed the subshell our keyboard input until it says it's finished */
995 feed_subshell (int how
, int fail_on_error
)
997 fd_set read_set
; /* For `select' */
999 int bytes
; /* For the return value from `read' */
1000 int i
; /* Loop counter */
1002 struct timeval wtime
; /* Maximum time we wait for the subshell */
1003 struct timeval
*wptr
;
1005 /* we wait up to 10 seconds if fail_on_error, forever otherwise */
1008 wptr
= fail_on_error
? &wtime
: NULL
;
1012 if (!subshell_alive
)
1015 /* Prepare the file-descriptor set and call `select' */
1017 FD_ZERO (&read_set
);
1018 FD_SET (subshell_pty
, &read_set
);
1019 FD_SET (subshell_pipe
[READ
], &read_set
);
1020 maxfdp
= max (subshell_pty
, subshell_pipe
[READ
]);
1023 FD_SET (STDIN_FILENO
, &read_set
);
1024 maxfdp
= max (maxfdp
, STDIN_FILENO
);
1027 if (select (maxfdp
+ 1, &read_set
, NULL
, NULL
, wptr
) == -1)
1030 /* Despite using SA_RESTART, we still have to check for this */
1032 continue; /* try all over again */
1033 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
1034 fprintf (stderr
, "select (FD_SETSIZE, &read_set...): %s\r\n",
1035 unix_error_string (errno
));
1036 exit (EXIT_FAILURE
);
1039 if (FD_ISSET (subshell_pty
, &read_set
))
1040 /* Read from the subshell, write to stdout */
1042 /* This loop improves performance by reducing context switches
1043 by a factor of 20 or so... unfortunately, it also hangs MC
1044 randomly, because of an apparent Linux bug. Investigate. */
1045 /* for (i=0; i<5; ++i) * FIXME -- experimental */
1047 bytes
= read (subshell_pty
, pty_buffer
, sizeof (pty_buffer
));
1049 /* The subshell has died */
1050 if (bytes
== -1 && errno
== EIO
&& !subshell_alive
)
1055 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
1056 fprintf (stderr
, "read (subshell_pty...): %s\r\n", unix_error_string (errno
));
1057 exit (EXIT_FAILURE
);
1061 write_all (STDOUT_FILENO
, pty_buffer
, bytes
);
1064 else if (FD_ISSET (subshell_pipe
[READ
], &read_set
))
1065 /* Read the subshell's CWD and capture its prompt */
1067 bytes
= read (subshell_pipe
[READ
], subshell_cwd
, MC_MAXPATHLEN
+ 1);
1070 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
1071 fprintf (stderr
, "read (subshell_pipe[READ]...): %s\r\n",
1072 unix_error_string (errno
));
1073 exit (EXIT_FAILURE
);
1076 subshell_cwd
[bytes
- 1] = 0; /* Squash the final '\n' */
1080 subshell_ready
= TRUE
;
1081 if (subshell_state
== RUNNING_COMMAND
)
1083 subshell_state
= INACTIVE
;
1088 else if (FD_ISSET (STDIN_FILENO
, &read_set
))
1089 /* Read from stdin, write to the subshell */
1091 bytes
= read (STDIN_FILENO
, pty_buffer
, sizeof (pty_buffer
));
1094 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
1096 "read (STDIN_FILENO, pty_buffer...): %s\r\n", unix_error_string (errno
));
1097 exit (EXIT_FAILURE
);
1100 for (i
= 0; i
< bytes
; ++i
)
1101 if (pty_buffer
[i
] == subshell_switch_key
)
1103 write_all (subshell_pty
, pty_buffer
, i
);
1105 subshell_state
= INACTIVE
;
1109 write_all (subshell_pty
, pty_buffer
, bytes
);
1111 if (pty_buffer
[bytes
- 1] == '\n' || pty_buffer
[bytes
- 1] == '\r')
1112 subshell_ready
= FALSE
;
1120 /* Wait until the subshell dies or stops. If it stops, make it resume. */
1121 /* Possibly modifies the globals `subshell_alive' and `subshell_stopped' */
1125 sigset_t sigchld_mask
, old_mask
;
1127 sigemptyset (&sigchld_mask
);
1128 sigaddset (&sigchld_mask
, SIGCHLD
);
1129 sigprocmask (SIG_BLOCK
, &sigchld_mask
, &old_mask
);
1132 * SIGCHLD should not be blocked, but we unblock it just in case.
1133 * This is known to be useful for cygwin 1.3.12 and older.
1135 sigdelset (&old_mask
, SIGCHLD
);
1137 /* Wait until the subshell has stopped */
1138 while (subshell_alive
&& !subshell_stopped
)
1139 sigsuspend (&old_mask
);
1141 if (subshell_state
!= ACTIVE
)
1143 /* Discard all remaining data from stdin to the subshell */
1144 tcflush (subshell_pty_slave
, TCIFLUSH
);
1147 subshell_stopped
= FALSE
;
1148 kill (subshell_pid
, SIGCONT
);
1150 sigprocmask (SIG_SETMASK
, &old_mask
, NULL
);
1151 /* We can't do any better without modifying the shell(s) */
1154 /* pty opening functions */
1158 /* System V version of pty_open_master */
1161 pty_open_master (char *pty_name
)
1166 #ifdef HAVE_POSIX_OPENPT
1167 pty_master
= posix_openpt (O_RDWR
);
1169 /* getpt () is a GNU extension (glibc 2.1.x) */
1170 pty_master
= getpt ();
1172 strcpy (pty_name
, "/dev/ptc");
1173 pty_master
= open (pty_name
, O_RDWR
);
1175 strcpy (pty_name
, "/dev/ptmx");
1176 pty_master
= open (pty_name
, O_RDWR
);
1179 if (pty_master
== -1)
1182 if (grantpt (pty_master
) == -1 /* Grant access to slave */
1183 || unlockpt (pty_master
) == -1 /* Clear slave's lock flag */
1184 || !(slave_name
= ptsname (pty_master
))) /* Get slave's name */
1189 strcpy (pty_name
, slave_name
);
1193 /* System V version of pty_open_slave */
1195 pty_open_slave (const char *pty_name
)
1197 int pty_slave
= open (pty_name
, O_RDWR
);
1199 if (pty_slave
== -1)
1201 fprintf (stderr
, "open (%s, O_RDWR): %s\r\n", pty_name
, unix_error_string (errno
));
1204 #if !defined(__osf__) && !defined(__linux__)
1205 #if defined (I_FIND) && defined (I_PUSH)
1206 if (!ioctl (pty_slave
, I_FIND
, "ptem"))
1207 if (ioctl (pty_slave
, I_PUSH
, "ptem") == -1)
1209 fprintf (stderr
, "ioctl (%d, I_PUSH, \"ptem\") failed: %s\r\n",
1210 pty_slave
, unix_error_string (errno
));
1215 if (!ioctl (pty_slave
, I_FIND
, "ldterm"))
1216 if (ioctl (pty_slave
, I_PUSH
, "ldterm") == -1)
1219 "ioctl (%d, I_PUSH, \"ldterm\") failed: %s\r\n",
1220 pty_slave
, unix_error_string (errno
));
1224 #if !defined(sgi) && !defined(__sgi)
1225 if (!ioctl (pty_slave
, I_FIND
, "ttcompat"))
1226 if (ioctl (pty_slave
, I_PUSH
, "ttcompat") == -1)
1229 "ioctl (%d, I_PUSH, \"ttcompat\") failed: %s\r\n",
1230 pty_slave
, unix_error_string (errno
));
1234 #endif /* sgi || __sgi */
1235 #endif /* I_FIND && I_PUSH */
1236 #endif /* __osf__ || __linux__ */
1238 fcntl (pty_slave
, F_SETFD
, FD_CLOEXEC
);
1242 #else /* !HAVE_GRANTPT */
1244 /* BSD version of pty_open_master */
1246 pty_open_master (char *pty_name
)
1249 const char *ptr1
, *ptr2
;
1251 strcpy (pty_name
, "/dev/ptyXX");
1252 for (ptr1
= "pqrstuvwxyzPQRST"; *ptr1
; ++ptr1
)
1254 pty_name
[8] = *ptr1
;
1255 for (ptr2
= "0123456789abcdef"; *ptr2
!= '\0'; ++ptr2
)
1257 pty_name
[9] = *ptr2
;
1259 /* Try to open master */
1260 pty_master
= open (pty_name
, O_RDWR
);
1261 if (pty_master
== -1)
1263 if (errno
== ENOENT
) /* Different from EIO */
1264 return -1; /* Out of pty devices */
1265 continue; /* Try next pty device */
1267 pty_name
[5] = 't'; /* Change "pty" to "tty" */
1268 if (access (pty_name
, 6) != 0)
1277 return -1; /* Ran out of pty devices */
1280 /* BSD version of pty_open_slave */
1282 pty_open_slave (const char *pty_name
)
1285 struct group
*group_info
= getgrnam ("tty");
1287 if (group_info
!= NULL
)
1289 /* The following two calls will only succeed if we are root */
1290 /* [Commented out while permissions problem is investigated] */
1291 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
1292 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
1294 pty_slave
= open (pty_name
, O_RDWR
);
1295 if (pty_slave
== -1)
1296 fprintf (stderr
, "open (pty_name, O_RDWR): %s\r\n", pty_name
);
1297 fcntl (pty_slave
, F_SETFD
, FD_CLOEXEC
);
1301 #endif /* !HAVE_GRANTPT */
1302 #endif /* HAVE_SUBSHELL_SUPPORT */